Professional Documents
Culture Documents
Inner Classes
Chapter 12
Inner Classes
Page 1
12 INNER CLASSES
Documentation Conventions
The following conventions are used in this guide:
Recall learning
Case study
Class session
Activity
Quiz
Reference
Page 2
12 INNER CLASSES
Page 3
12 INNER CLASSES
1. Inner Classes
1.1 Inner Classes
The class file whose name is present inside another class is called inner class. The scope of
this class is present inside its parent class. Thus they are invisible to other classes in the
same package. It is a non-static nested class. It is fully under the scope of its enclosing class.
The following program shows how an inner class is used.
Example program
//Program for inner class
class Outerone {
int outerone_z = 500;
void test() {
Innerone innerone = new Innerone();
innerone.display();
}
// this is the inner class
class Innerone {
void display() {
System.out.println("display: outerone_z = " +
outerone_z); }}}
class InnerClassDemo {
public static void main(String args[]) {
Outerone outerone = new Outerone();
outerone.test();
}
}
Output
Page 4
12 INNER CLASSES
In the above program an inner class named as “innerone” is defined within the scope of
class “outerone”. Therefore, any code in class innerone can directly access the variable
outerone. The display() method is defined inside innerone. This method displays outerone_x
in the output stream. An error message is displayed by the compiler if any code outside of
class outerone tries to instantiate the inner class.
Page 5
12 INNER CLASSES
Example program
interface IDrawable {
void draw();
}
class Shape implements IDrawable {
public void draw() { System.out.println("how to draw
a Shape."); }
}
class Painter { // Top-level
Class
public Shape createCircle(final double radius) { //
(4) Non-static Method
class Circle extends Shape { // Non-static
local class
public void draw() {
System.out.println("how to draw a Circle
of radius: " + radius);
} }
return new Circle(); // Object of
non-static local class
}
public static IDrawable createMap() { // Static
Method
class Map implements IDrawable { // Static
local class
Page 6
12 INNER CLASSES
Output
Page 7
12 INNER CLASSES
Page 8
12 INNER CLASSES
Instance initializer is a block of code inside curly braces that is embedded in a class
definition, where a field or method definition normally appears. A class can have any
number of instance initializers. They are executed in the order they appear in the code. They
are automatically run after the superclass constructor.
They are mostly useful for anonymous classes.
Page 9
12 INNER CLASSES
Page 10
12 INNER CLASSES
Output
Advantage
It does not need an object of the containing class to work. Hence it reduces the number of
objects that our application creates at runtime.
Exercise
Summary
From the above chapter we are familiar with
Inner classes
Local classes
Static nested classes
Anonymous classes
Page 11