How static class Object is created without reference of outer class in java?

Java 8Object Oriented ProgrammingProgramming

A static member (method/variable) belongs to the class and it will be loaded into the memory along with the class. You can invoke it without creating an object. (using the class name as reference). There is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword.

Example

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Value of num in the demo method "+ Sample.num);
   }
}
public class Demo{
   public static void main(String args[]){
      System.out.println("Value of num in the main method "+ Sample.num);
      Sample.demo();
   }
}

Output

Value of num in the main method 50
Value of num in the demo method 50

Referencing a static member from the same class

If you want to reference a static member of a class in itself (in the same class), there is no need of reference of the class, you can directly access the static members.

Example

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Value of num in the demo method "+ Sample.num);
   }
   public static void main(String args[]){
      demo();
      System.out.println(num);
   }
}

Output

Value of num in the demo method 50

Inner classes

In Java you can have classes within classes and they are known as inner classes.

Syntax

public class Outer{
   public class Inner{
   }
}

When you have a class within another class, it just acts as an instance member of the outer class. Therefore, if you declare an inner class static you can access the members of it (inner class) using its name as −

outer_class_name.inner_class_name.members

Example

class OuterDemo {
   static int data = 200;
   static class InnerDemo {
      public static void my_method() {
         System.out.println("This is my nested class");
         System.out.println(OuterDemo.data);
      }
   }
}
public class StaticClassExample{
   public static void main(String args[]) {
      System.out.println(OuterDemo.data);
      //Outer.InnerDemo nested = new Outer.InnerDemo();
      OuterDemo.InnerDemo.my_method();
   }
}

Output

200
This is my nested class
200

If you try to reference a (static) member of a static inner class there is no need to use the outer class name too you can just refer the meember using the inner class name (only).

Example

class OuterDemo {
   static int data = 200;
   static class InnerDemo {
      public static void my_method() {
         System.out.println("This is my nested class");
         System.out.println(OuterDemo.data);
      }
   }
   public static void main(String args[]) {
      System.out.println(data);
      InnerDemo.my_method();
   }
}

Output

200
This is my nested class
200
raja
Published on 05-Aug-2019 17:26:50
Advertisements