我有一个 2 类,其中一个扩展了父类(super class)。 当我从主类调用子类时,出现错误,因为“我调用的方法不是该类的一部分”,但随着我的程序继续运行,它应该可以工作 我只能在类选角时使用它,但我的老师告诉我,在这样的作品中不应该使用选角,所以请我想了解我哪里错了,哪里可以做得更好
(我提供了3个类的代码,子类,父类(super class)和主类)
主要
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Type in the number");
int number = in.nextInt();
System.out.print("Type in the name");
String name = in.next();
Test testObj = new Test(number);
testObj = new TestSub(number);
testObj.setNameSub(name);
in.close();
}
}
超一流
public class Test {
protected int number;
protected String name;
public Test(int number){
this.number=number;
}
public void setName(String name){
this.name=name;
}
public String toString(){
return "the name is "+name+"the number is "+number;
}
}
子类
public class TestSub extends Test {
public TestSub(int number){
super(number);
}
public void setNameSub(String name){
setName(name);
}
public String toStringSub(){
return toString();
}
}
我得到的错误是这样的:
The method setNameSub(String) is undefined for the type Test
在main中有这条指令:testObj.setNameSub(name);
最佳答案
这里的错误是(如注释中所示)您将 testObj 初始化为 Test 而不是 TestSub,当编译器无法在 Test 的方法之间找到 setNameSub() 时,会导致错误。
因此,简单的解决方案显然是将 testObj 初始化为 TestSub。
利用方法继承的正确解决方案是保持初始化不变,但改为调用方法 testObj.setName(name),并从 TestSub 类中删除 setNameSub() 和 toString() 方法,因为它们不要添加任何与 Test 类中的方法不同的内容。
关于java - 我对遗传类(class)的方法有疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58538176/