You are on page 1of 13

Chapter 12

Inner Classes

ICT Academy of Tamil Nadu


ELCOT Complex, 2-7 Developed Plots, Industrial Estate, Perungudi, Chennai 600 096.
Website : www.ictact.in , Email : contact@ictact.in ,
Phone : 044 4290 6800 , Fax : 044 4290 6820
Table of Contents

1. Inner Classes .................................................................................................... 4

1.1 Inner Classes.............................................................................................. 4

1.2 Member Classes ........................................................................................ 5

1.3 Local Classes .............................................................................................. 5

1.4 Anonymous Classes ................................................................................... 8

1.5 Instance Initializers .................................................................................... 8

1.6 Static Nested Classes ................................................................................10


12 INNER CLASSES

Chapter 12
Inner Classes

Page 1
12 INNER CLASSES

Documentation Conventions
The following conventions are used in this guide:

When you see this… This is…

Recall learning

Case study

Did you know?

Class session

Activity

Quiz

Reference

Indented text in different


Code snippet
font

Page 2
12 INNER CLASSES

Chapter 12: Inner Classes


In the following chapter we are going to deal with different types of classes namely inner
classes, local classes, anonymous classes etc. The nested classes are also discussed here.

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.

Rules of inner classes


- Inner classes cannot have static members, only static final variables.
- Interfaces are never inner
- Static classes are not inner classes.
- The static members may be inherited by inner classes that are not compile time
constants even though they may not declare them.

1.2 Member Classes


A member class is a class defined inside the body of a class. They can also use instances of
the same class. An object of an inner class must be internally linked to an object of the
enclosing class. Thus a member class is a true inner class.

Why we use member classes?


The main objective of using member classes is to access the other members of the class.
The methods of member class have direct access to all the members enclosing the members
of the enclosing classes. Hence it is mainly useful at instances where there is no reason for
an object of a member class to exist in the absence of an object of the enclosing class and
where the methods of the object of the member class need to access to members of the
object of the enclosing class.

1.3 Local Classes


A local class is a class defined within a block of Java code.
A local class is visible only within that particular block. The local classes are defined within
an enclosing class though they are not member classes. Hence they share many features of
member class.

Page 5
12 INNER CLASSES

The features of local classes are:


• They are only visible and usable within the block of code in which they are defined.
• They can use any final local variables or method parameters that are visible from the
scope in which they are defined.

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

public void draw() {


System.out.println("Drawing a Map."); }
} return new Map(); //
Object of static local class
}}
public class Local {
public static void main(String args[]) {
IDrawable[] drawables = { //
new Painter().createCircle(5),// Object of
non-static local class
Painter.createMap(), // Object of
static local class
new Painter().createMap() // Object of
static local class
};
for (int i = 0; i < drawables.length; i++) //
drawables[i].draw();
System.out.println("Local Class Names are:");
System.out.println(drawables[0].getClass()); //
System.out.println(drawables[1].getClass()); //
}
}

Output

Page 7
12 INNER CLASSES

1.4 Anonymous Classes


An anonymous class is a kind of local class that has no name. Instead of using a local class
and then instantiating it we can use an anonymous class to combine these two steps. It
combines the syntax for class definition with the syntax for object instantiation. While a
local class definition is a Java statement, an anonymous class definition (and instantiation) is
a Java expression, so it can appear as part of a larger expression, such as method invocation.
Interfaces cannot be defined anonymously.
The following are the cases in which an anonymous class can be used instead of local class:
- The class has a very short body.
- Only one instance of the class is needed.
- The class is used right after it is defined.
- The name of the class does not make your code any easier to understand.

Syntax to declare anonymous classes:


new<super classname>(<argument list>) {< class
declarations>}

1.5 Instance Initializers


The anonymous classes cannot define constructors, since they do not have names. Hence a
new feature was added known as instance initialize.
Example Program
public class DemoInitializer
{
// This is an instance variable.
public int[] a1;
// This is an instance initializer.
//It is a code that runs for every new instance, after
the superclass constructor
// and before the class constructor, if any. It can
serve the same

Page 8
12 INNER CLASSES

// function as a constructor with no arguments.


{
a1 = new int[10];
for(int i = 0; i < 10; i++) a1[i] = i;
}
// The line below contains another instance initializer.
The instance
// initializers for an object are run in the order in
which they appear
// in the class definition.
int[] a2 = new int[10]; { for(int i=0; i<10; i++) a2[i]
= i*2; }
static int[] static_array = new int[10];
// By contrast, the block below is a static
initializer. Note the static
// keyword. It runs only once, when the class is first
loaded.
static {
for(int i = 0; i < 10; i++) static_a[i] = i;
}
}

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

1.6 Static Nested Classes


A class within another class is said as nested classes. The scope of nested class is enclosed
within the enclosing class. The nested class is of two types
- Static
- Non-static
A static nested class is one in which the static modifier is applied. As it is static it can access
the members of its enclosing class through an object. It cannot refer to its member class
directly.
Static nested classes are accessed using the enclosing name
OuterClass.StaticNestedClass
To create an object to the nested class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Example Program
public class Outer{
int x = 300;
class Inner{
int x = 500;
public void check(){
System.out.println("Value of x is: "+
Outer.this.x );
}
}
public void check(){
new Inner().check();
}
public static void main(String args[]){
new Outer().check(); }
}

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

1. Write a program using local classes.

2. Write a program using anonymous classes

3. Why do we use instance initializers

Summary
From the above chapter we are familiar with
 Inner classes
 Local classes
 Static nested classes
 Anonymous classes

Page 11

You might also like