Lecture 3 Nested Classes
Lecture 3 Nested Classes
Nested Classes
In Java, just like methods, variables of a class too can have
another class as its member. Writing a class within another is
allowed in Java. The class written within is called the nested
class, and the class that holds the inner class is called the outer
class.
Syntax
class Outer_Demo {
class Nested_Demo {
}
}
Nested classes are divided into two types
Inner Class
Creating an inner class is quite simple. You just need to write a
class within a class. Unlike a class, an inner class can be private
1|P ag e
Data Structures and Algorithms
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}
}
}
Output
This is an inner class
2|P ag e
Data Structures and Algorithms
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method
of the inner class");
return num;
}
}
}
System.out.println(inner.getNum());
}
}
Output
This is the getnum method of the inner class
175
Method-local Inner Class
public class Outerclass {
// instance method of the outer class
void my_Method() {
int num = 23;
4|P ag e
Data Structures and Algorithms
5|P ag e