Attributes and polymorphism

前端 未结 1 595
失恋的感觉
失恋的感觉 2021-01-25 20:04

I have 2 classes:

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

class SubIncrease extends Increase{
           


        
相关标签:
1条回答
  • 2021-01-25 21:03

    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.

    0 讨论(0)
提交回复
热议问题