Java “trick”, redefining daughter class member

后端 未结 6 1009
青春惊慌失措
青春惊慌失措 2021-02-19 06:03

I\'m training for a Java exam, and I\'ve come across something I don\'t understand in last year subject. Here is the code

class Mother {
    int var = 2;

    in         


        
6条回答
  •  我寻月下人不归
    2021-02-19 07:05

    Methods can be overridden however fields can only be hidden. The difference is that a non-static method uses the type of the object referenced, a field takes the type of the reference. You see a similar thing with static methods which only be hidden where the class of the "reference" and the object (if provided) is ignored.

    For your interest, try giving the fields different types. ;)

    You can also try

    System.out.println(((Mother)m).var); // uses var in Mother
    System.out.println(((Daughter)m).var); // uses var in Daughter
    

提交回复
热议问题