Tuesday, February 27, 2018

What is different between static nested class and inner class(non-static class)

The main different is that,

Inner class requires - > Instantiation of outer class
static nested class    ->  Not Instantiation. Can directly access it.


Reference by -https://examples.javacodegeeks.com/java-basics/java-static-class-example/

static class  example

Wow Code-01

public class TestMain {

//Static class with static method
 public static class StaticNestedClass{
public static void staticNestedClass(){
System.out.println("StaticNestedClass");
}
}
 //Inner Class
public class InnerClass{
public void innerClass(){
System.out.println("Inner Class");
}
}

public static void main(String args[]){
//This is work because both class and method are static. Then we can directly call method
following bellow way
StaticNestedClass.staticNestedClass();
}

}

WOW CODE - 02

public class Application {
//There is two inner class call InnerClass And GO
public class InnerClass{
          public void innerClass(){
System.out.println("InnerClass");
}
public class GO{
public void go(){
System.out.println("go");
}
}
}

  //There is static class
public static class StaticClass{
public void staticClass(){
System.out.println("StaticClass");
}
}

//There is main method

public static void main(String[] args) {
 
   //If we need to call inner class
Application ap = new Application();

Application.InnerClass innerCls = ap.new InnerClass();
innerCls.innerClass();

//If we need to call inner inner class
Application.InnerClass.GO g = innerCls.new GO();
g.go();

//If we need to call static class
Application.StaticClass st = new StaticClass();
st.staticClass();
   
  //Or
  StaticClass st = new StaticClass();
st.staticClass();
  

}
}



No comments:

Post a Comment