属性和多态性 [英] Attributes and polymorphism

查看:110
本文介绍了属性和多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个班级:

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);

    }
}

但是当我跑

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

我得到了这个输出:

3
b13
3

任何人都可以帮助我理解为什么会这样?在方法add中更改了a属性的值,如第二个outpuy行所示...为什么它会恢复到原始值?

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?

推荐答案

在Java中,字段不会被覆盖,它们是隐藏的。这意味着 Increase.a SubIncrease.a 单独的字段,可以更改和单独查询。因为变量 f 的类型是增加,所以表达式 fa 返回超类字段的值。但 add()方法覆盖, f.add()调用子类方法,修改子类字段。

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.

这篇关于属性和多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆