Attributes and polymorphism

那年仲夏 提交于 2019-12-02 11:35:31

问题


I have 2 classes:

public class Increase {
public int a=3;
public void add(){
    a+=5;
    System.out.println("f");
}
}

class SubIncrease extends Increase{
    public int a=8;
    public void add(){
        a+=5;
        System.out.println("b" + a);

    }
}

But when I run

    Increase f=new SubIncrease();
    System.out.println(f.a);
    f.add();
    System.out.println(f.a);

I got this output:

3
b13
3

Could anyone help me to understand why this happens? The value of the a attribute was changed in method add, as shown by the second outpuy row...why does it get back to its original value?


回答1:


In Java, fields are not overridden, they are hidden. That means Increase.a and SubIncrease.a are separate fields that can be changed and queried separately. Because the type of your variable f is Increase, the expression f.a returns the value of the superclass field. But the add() method is overridden and f.add() calls the subclass method, which modifies the subclass field.

Hiding a field rarely makes sense, so you should avoid it. If you want to have a field with a different default value in a subclass, define it only in the superclass and assign a value to it in the subclass constructor.



来源:https://stackoverflow.com/questions/10411049/attributes-and-polymorphism

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!