![](/img/trans.png)
[英]Cyclic inheritance and interfaces - class A can't implement class B interface while class B implements A interface
[英]Extending class A with class B, but can't reach attributes of class A in class B methods
因此,如果我有两个这样的类:
public class A extends B{
public String name = "Alpha"
}
public class B{
public void revealAName(){
print(this.name);
}
}
main(){
A newA = new A();
newA.revealName();
}
在这种情况下,Eclipse表示属性名称不存在。 为什么这么说呢? 为什么我在B类的方法中不能使用A类对象的属性? 我该如何解决?
首先,应该只有一个公共类包含main方法。 其次,您正在使用继承。 因此,您必须将基类变量的访问修饰符设置为“ protected”才能访问子类。 因此,应为:
protected String name =“ Alpha”;
因为“默认”访问修饰符不允许访问子类。 从控制对班级成员的访问
Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N
另一件事,您使用“ this.name”试图获取类B的“ name”变量。这就是为什么它显示错误的原因。
使用继承时,您可以直接使用父类的变量,而无需使用任何对象引用;或者在变量名称重复的情况下,可以使用“ super”作为对象引用。 如有疑问,可以参考此图片 。
希望,现在会很清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.