繁体   English   中英

如何创建在 IntelliJ Idea 中编译的 Java 子 class?

[英]How do I create a Java child class that compiles in IntelliJ Idea?

以下是我在 Inheritance 上的代码:

class Noodle {

    double lengthInCentimeters;
    String shape;
    String texture = “brittle”;

    public void cook() {
      this.texture = "cooked";
    }

    public static void main(String args) {
      Spaghetti spaghettiPomodoro = new Spaghetti();
      System.out.println(spaghettiPomodoro.texture);
    }

 }

我搜索了一个解决方案,唯一接近我需要的建议如下:“如果您已经在项目视图中,请按 Alt+Insert (New) | Class。可以通过 Alt+1 激活项目视图。

要在与当前目录相同的目录中创建新的 class,请使用 Ctrl+Alt+Insert (New...)。

您也可以从导航栏中执行此操作,按 Alt+Home,然后使用箭头键选择 package,然后按 Alt+Insert。

另一个有用的快捷方式是查看 | Select 在 (Alt+F1), Project (1), 然后 Alt+Insert 在现有的附近创建一个 class 或使用箭头键导航包。

另一种方法是在现有代码中输入 class 名称,因为它尚不存在,IDEA 会以红色突出显示它,然后按 Alt+Enter 弹出 Intention Actions,选择创建 Class。”我试过这个:ctrl + alt + insert。这把我带到了一个 GUI,要求我命名 class,此外,从“类”、“接口”、“枚举”和“注释”中选择”。对于名称,我输入了“Spaghetti”,对于“Kind”,我选择了“Class”。这创建了一个看似子 class “Spaghetti”作为“Noodle”的子文件。我很高兴,因为没有红色曲线在我的代码中,但由于编译失败,我的幸福是短暂的。有人能告诉我我做错了什么吗?

无需使用快捷方式,您只需编写代码

我猜你的父母 class 名为Spaghetti 因此,您可以按如下方式编写代码:-

class Spaghetti{

        String texture = “brittle”;

        public void cook() {
          this.texture = "cooked";
        }
    }

Noodle class:

class Noodle extends Spaghetti{

        double lengthInCentimeters;
        String shape;
        String texture = “brittle”;

        public void cook() {
          this.texture = "cooked";
        }
    public static void main(String args) {
      Spaghetti spaghettiPomodoro = new Spaghetti(); //this is your parent class object
      System.out.println(spaghettiPomodoro.texture); //here you are calling instance 
                                                     //variable of parent class i.e. texture
      Noodle obj=new Noodle(); // this is child class object 
      System.out.println(obj.texture); //this will call child class instance variable "texture"

    }

 }

PS:-我建议您为主要方法制作一个单独的 class

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM