What is the purpose of creating static object in Java?

前端 未结 5 2063
走了就别回头了
走了就别回头了 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 11:08

    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();
     }
    

提交回复
热议问题