【问题标题】:Java: initialization of private variables in superclassJava:超类中私有变量的初始化
【发布时间】: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


【解决方案1】:

是的,它可以毫无问题地继承。如果在构造函数中没有赋值,你最终会得到默认值,因为它是一个实例成员。

Object 的默认值为 null,每个图元都有其默认值。

【讨论】:

  • 你的意思是因为我在构造函数之外给私有变量x赋值,所以赋值的值不会被继承而是会继承默认值?假设我将private int x = 0 行更改为private int x = 1,我会得到x 值作为子类中的默认0 还是1?谢谢。
  • 您将获得 1 :),因为它是实例成员并已分配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多