派生的 class 具有基础 class 私有成员

Derived class has base class private members

我有这个问题,我一直在思考它。我想弄清楚这实际上是如何工作的,为什么?

所以,我有这个 Base class:

public class Shape 
{
  private float width;
  private float height;

  public Shape(float width, float height) {
    this.width = width;
    this.height = height;
  }

  public void setWidth(float x){
    this.width = x;
  }

  public float getWidth() {
    return width;
  }

  public float getHeight() {
    return height;
  }
}

和这个派生的 class:

public class Rectangle extends Shape 
{
  public Rectangle(float width, float height) {
    super(width, height);
  }

  public float area (){
    float x = getHeight();
    float y = getWidth();
    return x*y;
  }
}

为什么导出的 class 使用 widthheight
我的意思是,我可以像这样实例化对象:

Shape s = new Shape(1,1);
Rectangle rect = new Rectangle(3,5);

Rectangle有变量widthheight。我正在使用基础 class 构造函数,但是当它通过 super(width, height) 时,它会到达 this.width = width 并且 height 也是如此。

什么是this.width
它只是基础的一种副本 class 还是它是如何工作的?

理解这里的关键是要注意在基础 class 构造函数中我们有两个 'width' 和 'height' 变量的变体:一个是 class object as such, other 是传递给构造函数的参数,每个都使用与另一个相同的名称

this.height = height; 获取构造函数 参数 的值并将其分配给 class 成员 。这有点奇怪,但可以很容易地在构造过程中直观地检查构造函数参数是否分配给了正确的 class 成员。

private float width;
private float height;

public Shape(float width, float height) {
this.width = width;
this.height = height;
}

以上代码中,全局变量为width、height。类似地,局部变量也是形状构造函数中存在的宽度和高度。所以我们使用这个关键字来区分局部变量和全局变量,因为它们具有相同的名称。