toString() 定义在抽象 class 的私有成员上,那么为什么打印 subclass 对象与抽象 class 的私有成员一起打印?

toString() defined on private members of abstract class,then why printing subclass object prints along with private members of abstract class?

摘要Class:

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);
}

子class:

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();
}

为什么 subclass pc 可以访问私有成员 x,y 摘要 class?根据继承规则,父 class 中的任何私有成员都不会继承到子 class 中,因此子 class 不应有任何成员 x、y。然而输出是:

0 --------- 2

没有。 toString() 继承自父 class。由于您没有在子 class 中覆盖此方法,并且因为它可以访问父 class 的私有变量,所以当调用 println 时,它只是打印父 class 的输出toString().

pc 无权访问 xy。它可以访问 toString(),因为这是一个 public 方法。 toString() 可以访问 xy,因为它是在 absclass.

中定义的