Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of creating static object in Java?

Tags:

java

class Demo {
   void show() {
      System.out.println("i am in show method of super class");
   }
}
class Flavor1Demo {

   //  An anonymous class with Demo as base class
   static Demo d = new Demo() {
       void show() {
           super.show();
           System.out.println("i am in Flavor1Demo class");
       }
   };
   public static void main(String[] args){
       d.show();
   }
}

In the above code, I do not understand the use of creating object d of Demo class with static keyword preceding it. If I eliminate the static keyword, it shows an error. Actually, I was going through anonymous inner class concept and got stuck here. Need help.... Can anyone please explain it?

like image 787
Ajay Khetan Avatar asked Jan 12 '17 10:01

Ajay Khetan


People also ask

What is the use of static object?

A "static" object is unique; it belongs to the class rather than the instance of the class. In other words, a static variable is only allocated to the memory once: when the class loads.

What is the purpose of static block in Java?

A static block, or static initialization block, is code that is run once for each time a class is loaded into memory. It is useful for setting up static variables or logging, which would then apply to every instance of the class.


1 Answers

The static keyword in Java means that the variable or function is shared between all instances of that class, not the actual objects themselves.

In your case, you try to access a resource in a static method,

public static void main(String[] args)

Thus anything we access here without creating an instance of the class Flavor1Demo has to be a static resource.

If you want to remove the static keyword from Demo class, your code should look like:

class Flavor1Demo {

// An anonymous class with Demo as base class
Demo d = new Demo() {
    void show() {
        super.show();
        System.out.println("i am in Flavor1Demo class");
    }
};

public static void main(String[] args) {

    Flavor1Demo flavor1Demo =  new Flavor1Demo();
    flavor1Demo.d.show();
}
}

Here you see, we have created an instance of Flavor1Demo and then get the non-static resource d The above code wont complain of compilation errors.

Hope it helps!

like image 183
Sourav Purakayastha Avatar answered Oct 13 '22 19:10

Sourav Purakayastha