【发布时间】:2016-08-19 14:07:11
【问题描述】:
在超类的构造函数之外初始化的私有变量会在子类中正确继承吗?
例如,在下面的代码中,私有实例变量 x 会在子类中正确继承吗?我知道只能使用 Rectangle 中定义的 2 个公共 getter 在 Square 子类中访问 x 和 y。但是,如果在构造函数之外初始化x,子类还能成功继承x吗?
public class Rectangle
{
private int x = 0;
private int y;
protected double height;
protected double length;
public Rectangle(double length, double height)
{
this.height = height;
this.length = length;
y = 0;
}
public int getx()
{
return x;
}
public int gety()
{
return y;
}
}
public class Square extends Rectangle
{
public Square(double side)
{
super(side, side);
}
}
【问题讨论】:
-
私有成员根本不被继承。但是,它们会根据程序文本进行初始化。
标签: java inheritance initialization