Name of the School: School of Computer Science and
Engineering
Course Code: E2UC304C Course Name:Java & Java Script
DEPARTMENT OF COMPUTER SCIENCE
& ENGINEERING
Subject Name: Java Programming
Day: 9
Topics Covered: Inner classes
1
Faculty Name: Programe Name: B.Tech (CSE,AI &ML)
Prerequisites, Objectives and Outcomes
Prerequisite of topic: Basic concepts related to java programming
Objective: To make students aware about the different types of inner
classes and use.
Outcome : 1. Student will be able to know about way to create inner class
2. Students will be able to understand various uses of inner class
3. Students will be able to implement in practical applications.
2
Inner Class
A class defined within another class is known as Nested class. The scope of the
nested class is bounded by the scope of its enclosing class.
Inner classes are defined inside the body of another class (known as outer class).
Inner class acts as a member of the enclosing class and can have any access
modifiers: abstract, final, public, protected , private, static.
Inner classes have special relationship with outer class instances.
Inner class can access all members of the outer class including those
marked private
3
Syntax of inner class:
class Outer
{
//class Outer members
class Inner
{
//class Inner members
}
} //closing of class Outer
4
Inner class and nested class
In Java, an inner class is also known as nested class.
Inner classes are part of nested classes.
Inner classes can be Static .
When a non-static class is defined in nested class then it is known as an inner class.
It is defined inside the class or an interface.
Inner classes are mostly used to logically group all the classes and the interface in one
place, which makes the code more readable and manageable.
Inner classes can access members of the outer class including all the private data
members and methods.
5
Advantage of Inner class
Inner classes are a security mechanism in Java.
We know a class cannot be associated with the access modifier
private, but if we have the class as a member of other class, then the
inner class can be made private.
And this is also used to access the private members of a class.
we make the inner class private and access the class
through a method.
6
Program of Private class
class Outer_Demo { public class My_class {
int num; public static void main(String args[]) {
// inner class //Instantiating the outer class
private class Inner_Demo { Outer_Demo outer = new
Outer_Demo();
public void print() { //Accessing the display_Inner()
System.out.println("This is an inner class"); method.
} outer.display_Inner();
} }
//Accessing the inner class from the method within }
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
7
inner class (Contd..)
An instance of an inner class cannot be created without an instance of the
outer class. Therefore, an inner class instance can access all of the members
of its outer class, without using a reference to the outer class instance.
Inner classes can be defined in four different following ways as
mentioned below:
1) Inner class
2) Method – local inner class
3) Anonymous inner class
4) Static nested class
8
1) Inner class program
An inner class is declared inside the curly braces of another enclosing class. Inner class is coded
inside a Top level class as
//Top level class definition
class MOClass {
private int myVar= 1;
// inner class definition
class MIClass {
public void seeOuter () {
System.out.println("Value of myVar is :" + myVar);
}
} // close inner class definition
} // close Top level class definition
9
1) Inner class sample
To instantiate an instance of inner class, there should be a live
instance of outer class.
▰ An inner class instance can be created only from an outer class
instance.
▰ An inner class shares a special relationship with an instance of the
enclosing class.
10
Program: inner class
//Instantiating an inner class from within code in outer class:
class MOClass {
private int a= 5; public static void main(String args[]){
class MIClass { // inner class definition MOClass obj = new MOClass();
obj.innerInstance();
public void seeOuter () {
}} // close Top level class definition
System.out.println("Outer Value of a is :" + a);
}
} // close inner class definition
public void innerInstance()
{
MIClass inner = new MIClass(); // object creation in a method
inner. seeOuter(); Output:
}
Outer Value of a is :5
11
Alternate Way of Instantiation
Instantiating an inner class from outside the outer class Instance
Code:
The public static void main code in the above example can be
replaced with this one. It will also give the same output.
public static void main(String args[]){
MOClass.MIClass inner = new MOClass().new MIClass();
inner. seeOuter();
}
12
Program Inner class
class MOClassD {
private int x= 1;
class MIClass { // inner class definition
public void seeOuter () {
System.out.println("Outer Value of x is :" + x);
}
} // close inner class definition
/* public void innerInstance()
{
MIClass inner = new MIClass();
inner. seeOuter();
} */
public static void main(String args[]){
MOClassD.MIClass inner = new MOClassD().new MIClass();
inner. seeOuter(); }
13 } // close Top level class definition
Program Inner class
class MOClassD {
private int x= 1;
class MIClass { // inner class definition
public void seeOuter () {
System.out.println("Outer Value of x is :" + x);
}
} // close inner class definition
/* public void innerInstance()
{
MIClass inner = new MIClass();
inner. seeOuter();
} */
public static void main(String args[]){
MOClassD2 outer = new MOClassD2 ();
MOClassD.MIClass inner = outer.new MIClass();
inner. seeOuter(); }
} // close Top level class definition
14
2) Method–Local inner classes
A method local inner class is defined within a method of the enclosing
class.
If you want to use inner class , you must instantiate the inner class in the
same method, but after the class definition code.
Only two modifiers are allowed for method-local inner class which
are abstract and final.
The inner class can use the local variables of the method (in which it is
present), only if they are marked final.
15
The above code will throw a
//Top level class definition compilation error as Inner class
cannot use the non-final variables of
class MOClass {
the method, in which it is defined.
private int a= 1; This is how it can be fixed: If we mark
public void meth1(){ the variable as final then inner class can
use it.
String name ="local variable";
// inner class defined inside a method of outer class final String name ="local variable";//
inner object can use it
class MIClass {
public void seeOuter () {
System.out.println("Outer Value of a is :" + a);
System.out.println("Value of name is :" + name); //compilation error!!
} //close inner class method
} // close inner class definition
} //close Top level class method
} // close Top level class
16
3) Anonymous Inner Classes
In Java, a class can contain another class known as nested class. It's
possible to create a nested class without giving any name.
A nested class that doesn't have any name is known as an anonymous class.
It should be used if you have to override method of class or interface.
Java Anonymous inner class can be created by two ways:
Class (may be abstract or concrete).
Interface
An anonymous class must be defined inside another class. Hence, it is also
known as an anonymous inner class.
17
Anonymous Class
Anonymous classes enable you to make your code more concise. They enable you to declare and
instantiate a class at the same time. They are like local classes except that they do not have a
name. Use them if you need to use a local class only once.
Basically, an anonymous inner class is a one-time class.
We define an anonymous inner class and create its object using the new operator at the same time in
one step.
The general syntax of the declaration of an anonymous class and its object is given below.
Type can be
class outerClass { a superclass that an anonymous class
// defining anonymous class
extends
2.an interface that an anonymous class
object1 = new Type(parameterList) {
implements
// body of the anonymous class The above code creates an object, object1,
}; of an anonymous class at runtime.
}
18
1. The new keyword is used to create an object of the anonymous inner class. It is
always followed by either an existing class name or an existing interface name.
2. if an interface name is used, it means that the anonymous class implements the
interface.
3. If a class name is used, it means that the anonymous class extends from the class.
4. It the new keyword is followed by a class name then the argument list is used only.
The argument list contains the actual parameter list which is used for calling a
constructor of the existing class.
5. If the new keyword is followed by an interface name, it is left empty.
6. Inside an anonymous class body, we can define variables, methods (if
necessary), instance block, and local class.
19
Anonymous Inner Classes
It is a type of inner class which
has no name
can be instantiated only once
is usually declared inside a method or a code block ,a curly braces ending with
semicolon.
is accessible only at the point where it is defined.
does not have a constructor simply because it does not have a name
cannot be static
20
When to use an Anonymous inner class in Java?
In general, there are the following points that you should consider using an anonymous
inner class instead of a local inner class.
1. The main purpose of using an anonymous inner class in java is just for instant use (i.e
one-time usage).
2. An anonymous inner class can be used if the class has a very short body.
3. It can be useful if only one object of the class is required.
4. An anonymous inner class is useful when you are writing implementation
classes for listener interfaces in graphics programming.
5. An anonymous inner class is the best suitable for GUI based application to implement
event handling
21
When we need Anonymous class
Note: 1. If the requirement is standard and required several times
then you should go for a normal top-level class.
2. If the requirement is temporary and required only once (instant
use), you should go for the anonymous inner class.
22
Features of Anonymous Inner Class in Java
An anonymous inner class in Java is a special kind of an inner class with the
following important features. They are as follows:
1. When an anonymous inner class is created, Internally, its name is decided by
the compiler which always extends a superclass or implements an interface. But
it cannot have an explicit extends or implements clause.
2. It must implement all the abstract methods of the superclass or of the
interface.
3. Internally, it always uses a default constructor from its superclass to create an
object.
23
Features of Anonymous Inner Class in Java
4. An anonymous inner class is compiled by a class
named OuterClassName$n. For example, if the outer
class Student has two anonymous inner classes, they are compiled
into Student$1.class and Student$2.class.
5. Like the local inner class, an anonymous inner class can also
access the members of its outer class.
24
Types of Anonymous Inner Class in Java
Based on declaration and behavior, an anonymous inner class in Java
comes into two flavors. They are as follows:
1. Anonymous inner class that extends a class
2. Anonymous inner class that implements an interface
25
1. A normal Java class can implement any number of interfaces simultaneously
Difference between Normal/Regular class and Anonymous Inner class
but an anonymous inner class can implement only one interface at a time.
2. A normal Java class can extend a class and can implement any number of
interfaces simultaneously but an anonymous inner class can extend a class
or can implement an interface but not both simultaneously.
3. In normal Java class, we can define any number of constructors but in an
anonymous inner class, we cannot write any constructor explicitly (because
the name of the class and name of the constructor must be the same but
anonymous inner class not having any name).
26
Program: Accessing child method using parent
class ref. variable
27
Program: Accessing child method using parent class ref.
variable
class India
{ public static void main(String
void show1() args[])
{ System.out.println("Student of India"); {
} India s1 = new Student();
void show2() s1.show3();
{ System.out.println("Student of IP"); }
}
}
}
class Student extends India // For this we get error method as we are
{ trying to access child class method using
void show3() parent class reference variable. So
correction required. This problem is
{
because of early binding.
System.out.println("Student of CSE");
Student s1 = new Student();
}
28
Program: Accessing child method using parent class ref.
variable
public static void main(String args[])
class India {
{ India s1 = new Student();
s1.show3();
void show1() }
{ System.out.println("Student of India"); }
}
void show2()
{ System.out.println("Student of IP");
}
}
// For this we do not get error method as we are trying
class Student extends India to access child class method using parent class
{ Overriding is taking
reference variable.
void show2() place which occurs at run time.
{ OUTPUT Student of CSE
System.out.println("Student of CSE");
}
29
Program Anonymous Class
class First {
public void showMe() { class ShowAnonymous
System.out.println("Hello from {
public static void main(String args[])
first"); {
} CallFirst cf=new CallFirst();
cf.f1.showMe();
} }
}
class CallFirst
{
First f1=new First(){
public void showMe()
{
System.out.println("modified Hello
from first");
}
};
30
}
Requirement of Anonymous class
public class Cow There are two ways by which we can
implement in the above code.
{ 1. We will create a class that will extend the
public void eat() Cow class and overrides the eat method.
But this technique is suitable for the permanent
{ requirement, not for the temporary requirement .
System.out.println(“Grass");
}
// Suppose we also declared here 5 more types of Cow eat() method.
So the total number of eat method will be 6.
}
Suppose we need eat potato plant for a one-time temporary requirement.
Except for this method, the remaining 5 methods we also want same eat grass.
31 Then how will you implement this in the above code?
Program showing anonymous class
class Cow
{ c.eat();
// This object is created for Cow class.
public void eat() { System.out.println("Grass"); } Cow c1 = new Cow();
} c1.eat(); // It will print sweet.
}
public class Food }
{
public static void main(String[] args)
{
// Here, we are using an anonymous inner class that extends a class Cow.
Cow c = new Cow() {
public void eat() // Here, Overriding the eat() method of Cow class.
{
System.out.println("plant"); // Overriding.
} }; // Anonymous inner class ends here. A semi-colon is necessary to end the statement.
32
Restriction on Anonymous inner class in Java
An anonymous inner class also has the same restriction as the local inner
class with respect to its members.
1. Anonymous inner class cannot be public, private, protected or static.
2. It cannot access the local variables of its enclosing scope that are not declared
as final or effectively final.
3. Inside anonymous inner classes, we cannot define any static variables,
methods, or static blocks except for static final constant.
4. We cannot create more than one object of the anonymous inner class in Java.
5. Since an anonymous inner class has no name. Therefore, we cannot declare a
constructor for it within the class body.
33
Program
class Animal{
public void eat() // here we are creating an anonymous
{ class and anonymous class has //been
System.out.println(“grass"); created at the time of object creation.
} Anonymous class is always a child
} class and object of annonymous class
class cow { is created using the name of parent
/* There is no semicolon(;) class and its constructor.
* semicolon is present at the curly braces of the method end. */
Animal a = new Animal(){ // Creating anonymous class
public void eat()
{
System.out.println("anonymous grass");
} };
}
34
Program
/* AnonymousClassDemo.java */
public class AnonymousClassDemo
{
public static void main(String[] args) class Dog
{
{ public void someDog()
Dog dog = new Dog() { {
System.out.println("Classic Dog");
public void someDog () }
{ }
System.out.println("Anonymous Dog");
}
}; // anonymous class body closes here
//dog contains an object of anonymous subclass of Dog.
dog.someDog();
}
}
35
Anonymous class with interface
//Java program to demonstrate Anonymous inner class
interface Animal
{
obj1.getAge();
int a = 21; }
void getAge(); }
}
class Anonymousshow
{
public static void main(String[] args) {
Animal obj1 = new Animal() { // We are creating object of anonymouse class without
//name and reference we are using of parent which is an interface.
@Override
public void getAge() {
System.out.print("Age is "+a); // printing age
}
36
};
4. Static nested classes
Static classes are basically a way of grouping classes together in Java.
Java doesn't allow you to create top-level static classes; only nested (inner) static
classes.
A static nested classes are the inner classes marked with static modifier. Because this is
static in nature so this type of inner class doesn’t share any special kind of
relationship with an instance of outer class.
A static nested class cannot access non static members of outer class.
Example:
class Outer{
static class Nested{}
}
37
Static nested method
A static nested class can be instantiated like this:
class Outer{// outer class
static class Nested{}// static nested class
}
class Demo{
public static void main(string[] args){
// use both class names, Static members are called with the class name,
//nested is member of Outer class that is why Outer is must before Nested one
Outer.Nested n= new Outer.Nested();
}
}
38
Differences between static and non-static nested
classes?
A static nested class may be instantiated without instantiating its
outer class.
Inner classes can access both static and non-static members of the
outer class.
A static class can access only the static members of the outer class.
39
1. static inner class with a static method
class outer
{
static class inner
{ public static void add(intx,int y)
{ int z = x + y;
System.out.println("add = " + z);
}
}
}
class innerclass_demo1
{ public static void main(String args[])
{
outer.inner.add(15,10);
}}
40
1. static inner class with a static method
class outer
{
int b=10;
static class inner
{ public static void add(int x, int y)
{ int z = x + y + b;
System.out.println("add = " + z);
}
} OUTPUT: Compile time error
} Static member can not call non static
member without the object
class innerclass_staticS
{ public static void main(String args[])
{
outer.inner.add(15, 10);
}}
41
2. Static inner class with non-static
method
class outer
{
static class inner
{ public void add(int x, int y)
{
int z = x + y;
System.out.println("add = " + z);
}
}
}
class innerclass_demo2
{ public static void main(String args[])
{ outer.inner ob = new outer.inner();
ob.add(12,13);
}}
42
2. static inner class with non-static method
class outer
{
static class inner
{ public void add(int x, int y)
{
int z = x + y;
System.out.println("add = " + z);
}
}
}
class innerclass_demo2
{ public static void main(String args[])
{ outer.inner ob = new outer.inner();
ob.add(12,13);
}}
43
References:
https://www.geeksforgeeks.org/
https://www.javatpoint.com/exception-handling-in-java
https://www.tutorialspoint.com/java/java_exceptions.htm
The complete reference, eleventh edition, available at:
https://gfgc.kar.nic.in/sirmv-science/GenericDocHandler/1
38-a2973dc6-c024-4d81-be6d-5c3344f232ce.pdf
44
Thank you
45