Monday, 16 October 2017

5. Non static nested class or Inner class

1. How to create an object for non static nested classes or Inner class?
  1. By using outer class refernce, we can create object for non static nested class or inner class.
class OuterClass {
   ...
   class InnerClass {
       ...
   }
}


OuterClass outerClass = new OuterClass();
OuterClass.StaticInnerClass staticInnerClass2 = outerClass.new StaticInnerClass();
  1. With in the Outer class we can directly create object without outer class name
OuterClass outerClass = new StaticInnerClass();
  1. In non static nested class we can define only instance members.


package com.nested;

public class OuterClass {
int i = 10;
static int j = 20;

void test() {
System.out.println("instance test");
System.out.println(new InnerClass().i);
new InnerClass().test();
System.out.println(new OuterClass.InnerClass().i);
}

class InnerClass {
int i = 100;
void test(){
System.out.println("I am in test InnerClass "+i);
System.out.println("I am in test OuterClass "+OuterClass.this.i);
}
}
}


package com.nested;

public class Main {
public static void main(String[] args) {
OuterClass o1 = new OuterClass();
o1.test();
//OuterClass.test();
OuterClass.InnerClass i1 = o1.new InnerClass();
}
}


2. Static nested class vs non static nested class?
Static Nested class
Non Static nested class (Inner class)
Static nested class object can be created through Outer class name only
Non static nested class can be created through Outer class reference only
Inside Static nested class we can declare both static and non static members
Inside non static nested class we can declare only non static members
OuterClass.StaticInnerClass i1 = new OuterClass.StaticInnerClass();
OuterClass o1 = new OuterClass();
OuterClass.InnerClass i1 = o1.new InnerClass();
We can’t get Outer class reference
We can get outer class reference (OuterClass.this)

No comments:

Post a Comment

3. Java Program to create Binary Tree