Egeio
Egeio

Reputation: 51

Which overridden methods are invoked?

I am having hard time to understand the solution of the given question. I can't understand at each step which of the class' methods are invoked.

I tried to make a list for what are a,b,c declared types and actual types then try to chose overridden or overloaded methods but it is complex.

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 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 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 Tester {

    public static void main(String[] args) {
    Lower a = new Lower(1);

    Middle b = a;

    Upper c = new Middle(5);



    a.set(c);

    b.set(a);

    c.set(b);

    System.out.println(a.show());
    System.out.println(b.show());
    System.out.println(c.show());

    }

}

What is printed as a result of System.out.println(a.show()); after the set commands? Answer is 1

What is printed as a result of System.out.println(b.show()); after the set commands? Answer is 1

What is printed as a result of System.out.println(c.show()); after the set commands? Answer is 1

I don't get why the answers of all these are 1. Also I can't tell which class' overridden or overloaded methods that "a.set(c); b.set(a); c.set(b);" uses. A detailed explanation would be really helpful.

Upvotes: 0

Views: 60

Answers (1)

floxbr
floxbr

Reputation: 154

a.set(c) uses the set-method from Middle, as that overrides the one from Upper and the (overloaded) set from Lower is not applicable because c is not an instance of Lower.

Therfore j is set to c.show() which returns c's attribute j, so it will be set to 5. Consequently the (Lower-)attribute i of a is never touched and remains at 1 when it is shown and printed.

Try to resolve the others yourself.

Upvotes: 1

Related Questions