Inner Classes
These are classes inside classes. Now these classes may seem to violate the OO concept but that is left to your discretion.
Creating them is as same as you create a normal class. The only catch is that here the class is treated somewhat like a class variable. You can have any access modifiers for it, which is not possible for a normal class. Normal classes are public or default.
Here is how you declare it.
Code:
classs OuterClass{
class InnerClass{
}
}
Here is the similarity between an a Class Variable and an inner class. Note that you can put any access specifier unlike the other class which is limited to a public and default.
Code:
class OuterClass{
private int d;
private class InnerClass{
}
}
The Code
Code:
public class InnerClass1 {
/*
* Execution starts here
*/
public static void main(String[] args) {
TheOuterOne.TheInnerOne obj = new TheOuterOne().new TheInnerOne();
obj.Display();
}
}
class TheOuterOne
{
private int x =1;
class TheInnerOne
{
public void Display()
{
System.out.println("The value of variable is "+x);
new TheInnerTwo(); //Making a new instance of the inner class
}
}
private class TheInnerTwo
{
public TheInnerTwo() {
System.out.println("Inside a private inner class.");
}
}
}
Output:
Code:
The value of variable is 1
Inside a private inner class.