[英]Java field hiding for attributes
我刚开始学习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()
,它发现只在Super
类中定义的toString()
方法因此使用该方法作为超类方法在子类中可用。 你的超类方法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());
}
}
你正在你的孩子班级中隐藏(遮蔽) str
。 由于您没有在子类中重写toString()
,因此调用是在父类中进行的,并且它会看到父类的str
。
如果你这样做:
public class Sub extends Super {
public Sub() {
this.str = "I'm sub.\n";
}
}
它会输出你所期望的。
这个调用是使用超类:
Sub s1 = new Sub();
System.out.printf(s1.toString());
原因是Sub没有覆盖 str
,它只是声明另一个恰好具有相同名称的变量。 换句话说,sub只是将变量隐藏在Super
(数据成员不是多态的)。
如果他们的意思不同,你可以给他们不同的名字。 或者可以使用getter方法对Sub
访问(或修改)父属性。
你没有为共享的超类字段分配字符串文字"I'm sub.\\n"
,你正在创建一个子类本地的字段并将其分配给它。
例如,
public class EncapsulationDemo {
public static void main(String[] args){
MySuperObject obj = new MySubObject();
System.out.println(obj); // prints I'm sub.
}
private static class MySuperObject{
String str = "I'm super."; // protected, can be accessed directly
// by subclasses
@Override
public String toString(){
return str;
}
}
private static class MySubObject extends MySuperObject{
MySubObject(){
super();
str = "I'm sub."; // assign to superclass field
}
}
}
有关更多信息,请参阅控制对类成员的访问 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.