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

在上面的代码中,我不明白在前面使用static关键字创建Demo类的对象d的用法。如果我删除 static 关键字,它会显示错误。实际上,我正在经历匿名内部类概念并被困在这里。需要帮助….任何人都可以解释一下吗?

原文由 Ajay Khetan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 517
2 个回答

Java 中的 static 关键字意味着变量或函数在该类的所有实例之间共享,而不是实际对象本身。

在您的情况下,您尝试以 static 方法访问资源,

 public static void main(String[] args)

因此,我们在此处访问的任何未创建类 Flavor1Demo 实例的内容都必须是 static 资源。

如果要从 Demo 类中删除 static 关键字,您的代码应如下所示:

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

在这里你看,我们创建了 Flavor1Demo 的实例,然后获取 non-static 资源 d 上面的代码不会抱怨编译错误。

希望能帮助到你!

原文由 Sourav Purakayastha 发布,翻译遵循 CC BY-SA 3.0 许可协议

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 方法是 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-static 无法从 static 上下文中引用对象。

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 方法。

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

原文由 Yousaf 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题