有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java子类setmethod不工作

public class RectangleEx extends Rectangle
{
    int height =0;
    int width=0;

    public RectangleEx(int height, int width)
    {
        super(height,width);
    }

    public RectangleEx()
    {
        super(0,0);
        this.setHeight(5);
        System.out.println(this.height);
    }
}

有谁能告诉我,为什么在使用第二个构造函数创建一个新的矩形时,它的高度是0而不是5?这是超类中setHeight的代码:

public void setHeight(int height)
{
    this.height = height;
}

共 (1) 个答案

  1. # 1 楼答案

    这是由于实例变量隐藏。由于在子类中声明了另一个同名变量height,因此它隐藏了在超类中定义的变量。因此,当您使用this.height访问变量时,将得到子类中定义的height的值,您根本没有设置它

    电话:

    this.setHeight(5); 
    

    调用super类的方法,该方法在super类本身中设置高度,而

    System.out.println(this.height);
    

    正在访问RectangleEx中定义的height,而不是Rectangle,后者仍然为0

    如果要访问超类的height,请在超类中定义一个getter,它将返回超类变量