InnerClasses

InnerClasses - Java Inner Classes What Is An Inner Class ?...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Java Inner Classes What Is An Inner Class ? An inner class is a class declared inside another class. When the outer class is compiled, two .class files are generated, one for the outer class and one for the inner class. Two objects exist at run time. There is no awareness of an "inner object" at run time. Objects are not instantiated inside each other! All objects must be instantiated with new - the instantiation of an object does not automatically instantiate objects from inner classes it may have declared. Why Would I Use An Inner Class ? An inner class is "in-line" code. When writing a GUI event adapter to catch window or mouse or key events, for example, it is often more convenient to create the "listener" class locally, inside the application class, rather than creating another class in a separate source file. Inner classes are also useful when creating a multithreading application by allowing the methods to be executed by different threads to be shown in the same source file. (See example in the multithread section of these Student Notes.) Example Of A Named Inner Class Here's an example of a class Outer that declares an inner class called Inner and uses it to return the date. (There's not much motivation here to use an inner class, but this simple example shows the syntax. ..) public class Outer extends ClassA { private Date d = new Date(); public class Inner extends ClassB { public Date getDate() { return d; } }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
public Date getDate() { Inner in = new Inner(); return in.getDate(); } } This Outer class could be used by another application class with the following code to get the date: Outer out = new Outer(); Date date = out.getDate(); When the Outer class is compiled, two .class files are produced, one called Outer.class and one called Outer$Inner.class. When the application instantiates the Outer object, the new operator uses the Outer.class file. When the getDate() method in the Outer class instantiates the Inner object, the new operator uses the Outer$Inner.class file to create the Inner object. The compiler gives the Inner object reference to its Outer object. This pointer is stored
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 6

InnerClasses - Java Inner Classes What Is An Inner Class ?...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online