overriding a variable in java

前端 未结 4 1344
我寻月下人不归
我寻月下人不归 2020-12-11 14:32
public class Foo {
      public int a = 3;
    public void addFive(){
        a += 5; System.out.print(\"f \");
    }
}

public class          


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 15:08

    I assume that you meant to declare an integer field a in class Foo.

    The answer to your question has to do with concepts of 'overriding' and 'hiding', as others have pointed out. Another way to explain it is that for member variables, there is no such thing as 'dynamic dispatch'. What that means is that, if you access a member of a certain object, the system checks at run time which member you mean, by looking at the class hierarchy.

    So, when calling the method f.addFive, at run time, the system will see that your object is actually a Bar and not a Foo, and so take the addFive function that you defined in the Bar class.

    That does not happen for member variables: you access f.a in your print statement, and at compile time it is decided that right there you want to access the field a declared in class Foo there -- and so, that is what will happen at run time.

    Now, the reason that there is no dynamic dispatch for member variable access is performance: it would be very expensive to go through the whole 'see what object this really is' logic every time you just want to add some value to a member variable.

提交回复
热议问题