简体   繁体   中英

Trouble understanding the output of a set of Java Objects

There are 4 classes:

class Lower extends Middle {
     private int i;
     private String name;
     public Lower(int i){
         super(i+1);
         name = "Lower";
         this.i = i;
     }
     public void set(Lower n){ i = n.show();}
     public int show(){return i;}
}

class Middle extends Upper {
    private int j;
    private String name;
    public Middle(int i){
        super(i+1);
        name = "Middle";
        this.j = i;
    }
    public void set(Upper n){ j = n.show();}
    public int show(){return j;}
} 

class Upper {
    private int i;
    private String name;
    public Upper(int i){
        name = "Upper";
        this.i = i;
    }
    public void set(Upper n){ i = n.show();}
    public int show(){return i;}
} 

class Tester {
    public static void main(String[] args){
        Lower a = new Lower(1);
        Middle b = a;
        Upper c = new Middle(5);
        System.out.println(a.show());
        System.out.println(b.show());
        System.out.println(c.show());
        a.set(c);
        b.set(a);
        c.set(b);
        System.out.println(a.show());
        System.out.println(b.show());
        System.out.println(c.show());
    }
}

I am quite confused by the output given by the 6 print statements in the tester class. The output that is given is 1, 1, 5, 1, 1, 1 but I was thinking that it should be 1, 1, 5, 5, 5, 5 instead. So clearly, my problem lies in understanding why the variable 'a' does not get set to 5 on the following line when all the lines after it seem to do that.

a.set(c);

Since although 'c' was declared to be of type Upper, it is actually a variable of type 'Middle' as it was set to the value of the 'Middle' variable 'b' in the tester. So the 'set' method that will be used should be the one in the 'Middle' class. By this logic, I thought the value of 'a' would be set to '5' but it seems that it remains as '1'. But I can't seem to figure out why.

Any help would be highly appreciated!

Your class Lower does not have a method set(Upper n) , it only has a method set(Lower n) . So when you make the call a.set(c); , it is forced to use the set(Upper n) method of its parent (in this case, of class Middle) which does have a set(Upper n) . This in turns sets j of Middle, but skipping i of Lower.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM