抽象类:
public abstract class absclass {
private int x,y;
public absclass(int x,int y) {
// TODO Auto-generated constructor stub
this.x=x;
this.y=y;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return new String(x+" --------- "+y);
}
子类:
public class pc extends absclass {
public pc(int x,int y) {
// TODO Auto-generated constructor stub
super(x, y);
// x=x;
// y=y;
}
public void compute()
{
System.out.println("well this is pc");
System.out.println(this);
//for y=1;
}
主要:
public static void main(String[] args) {
// TODO Auto-generated method stub
new pc(0, 2).compute();
}
为什么子类 pc 可以访问抽象类的私有(private)成员x,y?根据继承规则,父类中的任何私有(private)成员都不会继承到子类中,因此子类不应具有任何成员 x,y。然而输出是:
0 --------- 2
最佳答案
pc
无法访问 x
和 y
。它可以访问 toString()
,因为这是一个公共(public)方法。 toString()
可以访问 x
和 y
,因为它是在 absclass
中定义的。
关于java - toString() 定义在抽象类的私有(private)成员上,那么为什么打印子类对象会与抽象类的私有(private)成员一起打印呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49315582/