Java “trick”, redefining daughter class member

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

    I ran this in Eclipse and checked the values with debugger, the debugger actually shows the local m -variable having TWO different var -members after the m = new Daugher() -line with values 2 and 1. m.var seems to resolve to the one in Mother, and the m.getVar() calls the getVar in Daughter (as expected).

    However, when I change the main-method to look like this:

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

    It actually outputs 2, 2, 1, 1, so it would seem that the declaration of the variable affects which class's var is used.

提交回复
热议问题