Lecture2pptx 2024 08 28 22 03 17
Lecture2pptx 2024 08 28 22 03 17
Inner Classes
Inner classes, also called Nested
Classes, are nothing but classes that are
defined within other classes.
Here is a simple example of an inner class
class Outer
{
class inner
{
}
}
// Demonstrate an inner class.
class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner
{
void display() {
System.out.println("display: outer_x = " + outer_x);
}}}
class InnerClassDemo
{
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}}
public class OuterClass
{
private int x=10;
private static int y=20;
class Inner
{
public void m1()
{
System.out.println("instance variable..."+x+",static variable..."+y);
}
}
}
}
Types of Inner Classes
Inner classes nest within other classes.
Inner classes are of the following types:
1. Static Inner classes
2. Local Inner classes
3. Anonymous Inner classes
A Static Inner Class is a static
member of a class. Like any other static
method, a static member class has
access to all static methods of the
parent, or top-level, class.
new SuperType(construction
parameters)
{
inner class methods and data
}
Class Files generation for
Inner Classes
Each class can have more than one inner
classes. Once the main class is compiled
which has several inner classes, the
compiler generates separate class files for
each of the inner class.
public class Main
{
// Inner class Test1
class Test1
{
}
// Inner class Test2
class Test2
{
}
public static void main(String [] args)
{
// Anonymous inner class 1
new Object()
{};
// Anonymous inner class 2
new Object() {};
System.out.println("Hello World");
}
}