我刚刚开始学习 Java,所以如果答案有些明显,请耐心等待。我做了一些研究但没有结果。
据我了解,属性不会被覆盖,而只是隐藏字段。为了确定是否使用超类或子类中的属性,Java将检查引用的类型。
然后我不明白这里的输出:
public class Super {
String str = "I'm super!\n";
public String toString() {
return str;
}
}
public class Sub extends Super {
String str = "I'm sub.\n";
}
public class TestFH {
public static void main(String[] args) {
Sub s1 = new Sub();
System.out.printf(s1.toString());
}
}
它给了我:
I'm super!
我知道我可以通过方法重写轻松实现我想要的目标。我只是好奇幕后发生了什么。
提前致谢。
你打电话时,s1.toString()
,它发现toString()
方法仅定义在Super
类因此使用该方法,因为超类方法在子类中可用。你的超类方法toString()
正在使用它自己的类变量str
(在超类中初始化的值)作为方法的返回值以及因此的行为,即输出为I'm super!
.
如果你想得到输出为I'm sub.\n
那么您需要重用与超类中相同的变量并分配新的字符串值,即I'm sub.\n
到它。最好的选择是将构造函数用作:
public class Super {
String str = "I'm super!\n";
public Super(String stringValue){
this.str = stringValue;
}
public String toString() {
return str;
}
}
public class Sub extends Super {
public Sub(){
super("I'm sub.\n");
}
}
public class TestFH {
public static void main(String[] args) {
Sub s1 = new Sub();
System.out.printf(s1.toString());
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)