gpt4 book ai didi

java - 如何在继承的类中返回一个String?

转载 作者:行者123 更新时间:2023-12-02 03:13:33 25 4
gpt4 key购买 nike

所以我创建了一个名为“Food”的父类(super class),它接受一个名为“name”的字符串作为参数,现在我想创建一个名为“Meat”的继承类,并为该类指定它继承的名称“Meat”来自食品类。这是我当前的尝试:

public class Meat extends Food 
{
public Meat(String name) {
String meat = name;
}


public String getName() {
return name;
}
}

这是食品类:

public class Food {

//field that stores the name of the food
public String name;

//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}

public String getName() {
return name;
}
}

我目前不确定如何编写 Meat 构造函数来分配名称。感谢任何帮助,谢谢。

最佳答案

您需要从子构造函数调用 super 构造函数:

public class Meat extends Food {    
public Meat(String name) {
super(name);
}
}

阅读tutorial about super .

关于java - 如何在继承的类中返回一个String?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40687028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com