1. Types of Nested classes?
- There are four kinds of nested class in Java.
- static class: declared as a static member of another class
- inner class: declared as an instance member of another class
- local inner class: declared inside an instance method of another class
- anonymous inner class: like a local inner class, but written as an expression which returns a one-off object
2. How to create an object for static nested classes?
- By using outer class name, we can create object for static nested class.
class OuterClass {
... static class InnerClass { ... } } |
OuterClass.StaticInnerClass staticInnerClass = new OuterClass.StaticInnerClass();
|
- We can’t create object for static nested class with outer class reference.
OuterClass outerClass = new OuterClass();
OuterClass.StaticInnerClass staticInnerClass2 = new outerClass.StaticInnerClass();
|
- With in the Outer class we can directly create object without outer class name
OuterClass outerClass = new StaticInnerClass();
|
- In static nested class we can define both static members and instance members.
package com.nested;
public class OuterClass {
int i = 1;
static int j = 1;
public void test() {
//directly calling static members from outer class
main();
new StaticInnerClass();
new OuterClass.StaticInnerClass();
//Print static member of static nested class
System.out.println(StaticInnerClass.j);
//Print instance member of static nested class
System.out.println(new StaticInnerClass().i);
}
public static void main(){
System.out.println("static main");
}
public static class StaticInnerClass {
int i = 2;
static int j = 2;
}
}
|
package com.nested;
public class Main {
public static void main(String[] args) {
//Create an object for outer class
OuterClass outerClass = new OuterClass();
//Create an object for StaticInnerClass class
OuterClass.StaticInnerClass staticInnerClass = new OuterClass.StaticInnerClass();
System.out.println(staticInnerClass.i);
System.out.println(OuterClass.StaticInnerClass.j);
System.out.println(OuterClass.j);
System.out.println(outerClass.i);
}
}
|
No comments:
Post a Comment