Professional Documents
Culture Documents
Lecture Objectives
Learn about inner classes. Know the differences between static and nonstatic inner classes. Designing and using inner classes. Using local classes. Anonymous inner classes. Using inner classes for event handlers and listeners.
There are four categories of inner classes in Java: 1. Inner classes (non-static). 2. Static inner classes.
Used with GUIs
1. Local classes (defined inside a block of Java code). 2. Anonymous classes (defined inside a block of Java code).
Using an inner class as a helping class is one of the most useful applications of inner classes.
If used as a helping class, an inner class should be marked private.
Tip: Inner and Outer Classes Have Access to Each Other's Private Members (as with GUIs)
Within the definition of a method of an inner class:
It is legal to reference a private instance variable of the outer class It is legal to invoke a private method of the outer class.
Within the definition of the inner or outer classes, the modifiers public and private are equivalent.
There are certain situations, however, when an inner class must be static.
If an object of the inner class is created within a static method of the outer class. If the inner class must have static members.
To invoke a static method or to name a static variable of a static inner class within the outer class, preface each with the name of the inner class and a dot.
account.new
Note that the prefix account. must come before new The new object amount can now invoke methods from the inner class, but only from the inner class
using this inside an inner class refers to the object of the inner class.
An outer class can be a derived class. An inner class can be a derived class also.
Local Classes
A local class is defined within a block of Java code. Local classes are completely hidden in their containing block. When a class name is used only within a block it can be defined locally. A local class can access instance variables of the outer class and only the final local variables of the enclosing block.
Anonymous Classes
It is a local class without a name. If only one object has to be created from a class, and there is no need to name the class, then an anonymous class definition can be used
The class definition is embedded inside the expression with the new operator
Anonymous class has no constructors It is either derived from a class, or implements an interface. Like:
AnInterface i = new AnInterface ( ) { // methods defs. } ASuperclass c = new ASuperclass() { // methods defs. }
When this approach is used, each class is usually made a private inner class