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



下面是我关于继承的代码:

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(新建(|Class。项目视图可以通过Alt+1激活。

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

您也可以在导航栏中执行此操作,按Alt+Home,然后选择带箭头键的软件包,然后按Alt+Insert。

另一个有用的快捷方式是查看|选择在中(Alt+F1(、项目(1(,然后Alt+Insert在现有类附近创建一个类,或者使用箭头键在包中导航。

还有一种方法是,只需在现有代码中您想要使用的地方键入类名,IDEA会用红色突出显示它,因为它还不存在,然后按Alt+Enter键弹出Intention Actions,选择Create class。"我试过这个:ctrl+alt+insert。这让我进入了一个GUI,在那里我被要求命名类,此外,还可以从"class"、"Interface"、"Enum"one_answers"Annotation"中进行选择。我输入的名字是"意大利面条",而"善良",我选择了"阶级"。这创建了一个看似儿童类的"意大利面条",作为"面条"的子文件。我很高兴,因为我的代码中没有红色的歪歪扭扭,但我的快乐是短暂的,因为编译失败了。有人能告诉我我做错了什么吗?

不使用快捷键,只需编写代码

我猜您的父类名为Spaghetti。因此,您可以按照以下方式编写代码:-

class Spaghetti{
String texture = “brittle”;
public void cook() {
this.texture = "cooked";
}
}

Noodle类:

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"
}
}

第页。S: -我建议你为主方法制作一个单独的类

最新更新