I have the following code:
class Hello {
class Thing {
public int size;
Thing() {
size = 0;
}
}
public stat
Well... so many good answers but i wanna to add more on it. A brief look on Inner class in Java- Java allows us to define a class within another class and Being able to nest classes in this way has certain advantages:
It can hide(It increases encapsulation) the class from other classes - especially relevant if the class is only being used by the class it is contained within. In this case there is no need for the outside world to know about it.
It can make code more maintainable as the classes are logically grouped together around where they are needed.
The inner class has access to the instance variables and methods of its containing class.
We have mainly three types of Inner Classes
Some of the important points to be remember
Let`s try to see the above concepts practically_
public class MyInnerClass {
public static void main(String args[]) throws InterruptedException {
// direct access to inner class method
new MyInnerClass.StaticInnerClass().staticInnerClassMethod();
// static inner class reference object
StaticInnerClass staticInnerclass = new StaticInnerClass();
staticInnerclass.staticInnerClassMethod();
// access local inner class
LocalInnerClass localInnerClass = new MyInnerClass().new LocalInnerClass();
localInnerClass.localInnerClassMethod();
/*
* Pay attention to the opening curly braces and the fact that there's a
* semicolon at the very end, once the anonymous class is created:
*/
/*
AnonymousClass anonymousClass = new AnonymousClass() {
// your code goes here...
};*/
}
// static inner class
static class StaticInnerClass {
public void staticInnerClassMethod() {
System.out.println("Hay... from Static Inner class!");
}
}
// local inner class
class LocalInnerClass {
public void localInnerClassMethod() {
System.out.println("Hay... from local Inner class!");
}
}
}
I hope this will helps to everyone. Please refer for more