What is the purpose of creating static object in Java?

前端 未结 5 2064
走了就别回头了
走了就别回头了 2021-02-06 10:36
class Demo {
   void show() {
      System.out.println(\"i am in show method of super class\");
   }
}
class Flavor1Demo {

   //  An anonymous class with Demo as base c         


        
5条回答
  •  终归单人心
    2021-02-06 10:56

    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!

提交回复
热议问题