在Java中继承隐藏字段(Hiding Fields in Java Inheritance)

2019-06-27 17:57发布

在一类,具有相同的名称作为超一个字段的字段隐藏超类的领域。

public class Test {

    public static void main(String[] args) {

        Father father = new Son();
        System.out.println(father.i); //why 1?
        System.out.println(father.getI());  //2
        System.out.println(father.j);  //why 10?
        System.out.println(father.getJ()); //why 10?

        System.out.println();

        Son son = new Son();
        System.out.println(son.i);  //2 
        System.out.println(son.getI()); //2
        System.out.println(son.j); //20
        System.out.println(son.getJ()); //why 10?
    }  
}

class Son extends Father {

    int i = 2;
    int j = 20;

    @Override
    public int getI() {
        return i;
    }
}

class Father {

    int i = 1;
    int j = 10;

    public int getI() {
        return i;
    }

    public int getJ() {
        return j;
    }
}

有人可以解释的结果吗?

Answer 1:

在Java中,字段是不是多态。

Father father = new Son();
System.out.println(father.i); //why 1? Ans : reference is of type father, so 1 (fields are not polymorphic)
System.out.println(father.getI());  //2 : overridden method called
System.out.println(father.j);  //why 10? Ans : reference is of type father, so 2
System.out.println(father.getJ()); //why 10? there is not overridden getJ() method in Son class, so father.getJ() is called

System.out.println();

// same explaination as above for following 
Son son = new Son();
System.out.println(son.i);  //2 
System.out.println(son.getI()); //2
System.out.println(son.j); //20
System.out.println(son.getJ()); //why 10?


Answer 2:

按照重写和隐藏方法

这被调用隐藏方法的版本取决于它是否是从超类或子类调用。

即,当调用该子类中经由一个超类引用被调用超类方法覆盖的方法和它访问超类成员。

这就解释了以下作为所使用的参考是超类:

System.out.println(father.i);  //why 1?
System.out.println(father.j);  //why 10?
System.out.println(father.getJ()); //why 10?

同样,对于以下内容:

System.out.println(son.getJ()); //why 10?

因为getJ()中没有定义Son一个Father版本被调用它认为在所定义的部件Father类。

如果你读了隐藏字段 ; 他们专门不建议编码为这样的方法

一般来说,我们不建议隐藏字段,因为它使代码难以阅读。



文章来源: Hiding Fields in Java Inheritance