What is the purpose of creating static object in Java?

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!


You get an error by removing static keyword from static Demo d = new Demo() because you are using that object d of class Demo in main method which is static. When you remove static keyword from static Demo d = new Demo(), you are making object d of your Demo class non-static and non-staticobject cannot be referenced from a static context.

If you remove d.show(); from main method and also remove static keyword from static Demo d = new Demo(), you won't get the error.

Now if you want to call the show method of Demo class, you would have to create an object of your Demo class inside main method.

public static void main(String[] args){
     Demo d = new Demo(); 
     d.show();
 }

Tags:

Java