A Funny Java Flavoured Look at the World

Sunday, May 07, 2006

Nested Classes and how they work

One of the most confusing parts of Java our nested classes. The syntax can be very tricky with classes inside methods and methods overwriting others and semi colons on the end of curly brackets, the bottom line is it can be be very confusing.

Nested classes are probably one of the biggest SCJP Java 5 exam gotchas out there. The Java exam has a will not compile option on every question and inner classes makes this option very tricky because there syntax can look wrong and make the code look like it won't compile.

The examples are from the book Hardcore Java here is a link to the book if you are interesting in it http://www.oreilly.com/catalog/hardcorejv/

I also linked to another free PDF from this book which is a sample chapter on using the final keyword. Click the link to read my blog on the chapter and there is a link to the free pdf on final classes http://hoskinator.blogspot.com/2006/04/hardcore-java-final-story.html. I really like the two sample chapters I have read from Hardcore Java here is a quote about the book from the OReilly website
"Hardcore Java takes this language and breaks it apart, piece by piece, revealing the important secrets and tricks that will take you from a junior-level programmer to a seasoned and expert developer."
nested classes in Java is one of the more confusing concepts and can make reading someone else's code very confusing, especially if you are not to sure how nested classes work. The chapter also squashes the myth/misinterpretation that Static nested classes are inner classes. With most things in Java the best way to understand the programming concepts being talked about is to give examples and this sample chapter gives lots of examples.

if you don't understand inner classes I would recommend reading these articles because they can be very useful. The way I look at Inner classes is that they are like composition and using another class in your code, except the inner class has access to all of your private variables, which is a big advantage. If you are studying for the SCJP exam I definitely recommed you read these articles because you will see a lot of inner class code in the exam and you must be able to tell what is legal and illegal code otherwise you could be throwing away a lot of marks by not being able to spot the difference.

The articles talk about these topics and each article looks at each topic in some depth

Inner Classes
Limited Scope Inner Classes
Static Nested Classes

Here are the links

Nested Classes, Part 1 - Inner Classes
http://www.onjava.com/pub/a/onjava/excerpt/HardcoreJava_chap06/index.html
Nested Classes, Part 2 - Limited Scope Inner Classes
http://www.onjava.com/pub/a/onjava/excerpt/HardcoreJava_chap06/index1.html
Nested Classes, Part 3 - Static Nested Classes
http://www.onjava.com/pub/a/onjava/excerpt/HardcoreJava_chap06/index2.html

4 Comments:

Post a Comment

<< Home