Java “trick”, redefining daughter class member

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

    I read the answers and non of them (so far) gave good reason why in Object oriented language as Java is, this should be the case. I will try to explain.

    Suppose that you have function that takes Mother as arg:

    void foo(Mother m) {
      print(m.var);
    }
    

    This function (actually the compiler) has no idea if you will call it with Mother, Daughter or with another Dauther2 that doesn't even have var variable declared. Because of that, when the reference is of type Mother, reference to a member variable must be linked (by the compiler) to the Mother's member. The similar applies to function too, so the functions are linked to Mother's declaration of getVar(), but not to Mother's implementation of getVar()

    So, member variables are always linked (by the compiler) based on the reference. Another way to explain it: If you remove Mother's var (and make Mother's getVar() compilable), your second m.var (when m refers to Daughter) won't compile even Daughter has member var.

    I hope i was clear.

提交回复
热议问题