gpt4 book ai didi

java - toString() 定义在抽象类的私有(private)成员上,那么为什么打印子类对象会与抽象类的私有(private)成员一起打印呢?

转载 作者:行者123 更新时间:2023-12-01 07:18:25 25 4
gpt4 key购买 nike

抽象类:

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 无法访问 xy。它可以访问 toString(),因为这是一个公共(public)方法。 toString() 可以访问 xy,因为它是在 absclass 中定义的。

关于java - toString() 定义在抽象类的私有(private)成员上,那么为什么打印子类对象会与抽象类的私有(private)成员一起打印呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49315582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com