Wednesday, 18 July 2018

SE - 23 - Nested class in Java

Java supports two type of nesting :

1) Static nested class
2) inner nested class

Lets take a code example :

Here we have created a inner nested class and static nested class
public class mainclass {
 //inner nested class
 public class subclass{
  //method inside inner nested class
  public void method1() {
    
    System.out.println("inner nested class");
   }
  }
 //static nested class
 public static class substaticclass{
  //method inside static nested class
  public void method2() {
   
   System.out.println("nested static class");
  }
 } 
}

In the below code we are calling the methods created in the inner nested class and static nested class in above code :
public class classCall {

 @Test
 public void callm() {
  //calling a inner class
  mainclass x = new mainclass();
  mainclass.subclass z = x.new subclass();
  z.method1();
  
  //calling a static class
  mainclass.substaticclass c = new mainclass.substaticclass();
  c.method2();
 }
}

Output:
inner nested class
nested static class

So here we can see clearly that the members of static classes can be called directly by class name. For the inner class object we need to create reference of the outer class then call the members of the inner class.


No comments:

Post a Comment