Monday, 16 October 2017

4. Static nested class

1. Types of Nested classes?
  1. There are four kinds of nested class in Java.
    1. static class: declared as a static member of another class
    2. inner class: declared as an instance member of another class
    3. local inner class: declared inside an instance method of another class
    4. 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?
  1. By using outer class name, we can create object for static nested class.
class OuterClass {
   ...
  static  class InnerClass {
       ...
   }
}

OuterClass.StaticInnerClass staticInnerClass = new OuterClass.StaticInnerClass();
  1. We can’t create object for static nested class with outer class reference.
OuterClass outerClass = new OuterClass();
OuterClass.StaticInnerClass staticInnerClass2 = new outerClass.StaticInnerClass();
  1. With in the Outer class we can directly create object without outer class name
OuterClass outerClass = new StaticInnerClass();
  1. 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

3. Java Program to create Binary Tree