Java “trick”, redefining daughter class member

后端 未结 6 994
青春惊慌失措
青春惊慌失措 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 06:49

    Focus on these lines:

    Mother m;
     m = new Daughter();
     System.out.println(m.var);
     System.out.println(m.getVar());
    

    You are constructing a Daughter object, but you are treating it like it's base class Mother. So when you access m.var you are accessing the base class variable var. Meanwhile when you call a method, even if you are referring to the base class reference, the overrided method is called. It's a different behavior for methods and fields.. Fields reference cannot be overrided.

提交回复
热议问题