java中的变量隐藏

java中的变量隐藏,java,Java,请看下面的代码: class Rodent { protected int tailLength = 4; public void getRodentDetails() { System.out.println(this.tailLength); } } public class Mouse extends Rodent { protected int tailLength = 8; public static void main

请看下面的代码:

class Rodent {

    protected int tailLength = 4;

    public void getRodentDetails() {
        System.out.println(this.tailLength);
    }
}

public class Mouse extends Rodent {
    protected  int tailLength = 8;

    public static void main(String[] args) {
        Mouse mouse = new Mouse();
        mouse.getRodentDetails();
    }
}
现在继承了
getDetails()
。 当被
鼠标
引用调用时,
this.tailLength
应打印
8
而不是
4
,因为父
tailLength
隐藏在鼠标中

为什么打印4


编辑:问题不在于什么是变量隐藏,也不在于如何尝试覆盖变量。最接近的答案是JB Nizet在我下面扩展为答案的注释中给出的。

变量不会像您应该在构造函数中初始化的函数一样被重写

    public Mouse (){
     super.tailLength = 8;
    }
通过定义它,可以使Java中的鼠标类未知的其他变量成为方法,而不是属性。但是你可以把它们藏起来

因此,每当您在
Mouse
类中调用
tailLength
属性时,都会隐藏
tailLength
啮齿动物类中的属性,并使用
Mouse
类中的值

如果要覆盖此值,应使用以下结构:

class Rodent {
    // we add final to make sure value is always set
    protected final int tailLength;

    // default constructor
    protected Rodent() { this(4); }
    // use to overwrite tailLength  value
    protected Rodent(int tailLength ) { this.tailLength =tailLength; }

    public void getRodentDetails() {
        System.out.println(this.tailLength);
    }
}
还有鼠标类:

public class Mouse extends Rodent {
    public Mouse (){
      super(8);
    }
    ...
}
这样,您就可以在不进行任何覆盖的情况下设置尾部长度,但只需使用OOP即可。

这是因为

1) Java中的静态绑定发生在编译时,而动态绑定发生在编译时 绑定在运行时发生

2)私有方法、final方法以及静态方法和变量使用静态绑定并由编译器绑定,而虚拟方法是 基于运行时对象在运行时绑定。

3) 静态绑定使用类型(Java中的类)信息进行绑定 而动态绑定使用对象来解析绑定

4) 重载方法在重写时使用静态绑定进行绑定 方法在运行时使用动态绑定进行绑定

所以

在这段代码中,tailLength仅在编译时与啮齿动物类的tailLength变量相关联

为什么这个
没有影响它? 这是因为
此在运行时解析为内存地址


有人说这是因为变量隐藏,但变量隐藏本身是因为静态绑定。

因为字段不是多态解析的。只能使用实例方法。若要利用多态性,可以向每个类添加一个方法
getTailLength()
,该类返回特定于类的
tailLength
。如果鼠标来自啮齿动物,为什么要再次声明tailLength?;)错误的推导方式。有些人说这是由于变量隐藏,但变量隐藏本身是因为静态绑定-->而发生的,所以它是变量隐藏!
protected int tailLength = 4;

public void getRodentDetails() {
    System.out.println(this.tailLength);
}