0

This is for an ungraded recitation assignment for a 200 level CS course at my University. I am just asking for my own understanding.

In the following code, why does line 4 print B and A instead of B and B? Also, in Intellij I am told that the objs after the A in A.show(D obj) and B.show(B obj) are not used, while the A.show(A obj) and A.show(B obj) are used, even though they are seemingly both used the same way; just to identify which overloaded method to use.

public class Polymor {
    class A {
        public String show(D obj) {
            return ("A and D");
        }
        public String show(A obj) {
            return ("A and A");
        }
    }
    class B extends A {
        public String show(B obj) {
            return ("B and B");
        }
        public String show(A obj) {
            return ("B and A");
        }   
    }
    class C extends B {}
    class D extends B {}

    public static void main(String[] args) {
        Polymor outerclass = new Polymor();
        A a1 = outerclass.new A();
        A a2 = outerclass.new B();
        B b = outerclass.new B();
        C c = outerclass.new C();
        D d = outerclass.new D();
        System.out.println("1:" + a1.show(b));
        System.out.println("2:" + a1.show(c));
        System.out.println("3:" + a1.show(d));

        System.out.println("4:" + a2.show(b));
        System.out.println("5:" + a2.show(c));
        System.out.println("6:" + a2.show(d));

        System.out.println("7:" + b.show(b));
        System.out.println("8:" + b.show(c));
        System.out.println("9:" + b.show(d));
    }
}

I understand all of the outputs except for the ones I mentioned. I have searched online for this unused parameter issue but cannot find anything.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Welcome to the site. I have tried to make your code readable. For the future, please indent your code readably, and see [How do I format my code blocks?](https://meta.stackoverflow.com/q/251361/3890632) – khelwood Mar 24 '22 at 14:36
  • There are so many posts dealing with overloaded and overridden methods. Please read them. – Seelenvirtuose Mar 24 '22 at 14:40
  • As a quick answer: Your variable _a2_ is declared with type `A`. So, when creating bytecode for the call `a2.show(b)`, the compiler looks for the best fit in that type. And there is only one: `A.show(A obj)`. At runtime, the object referred to by _a2_ is of type `B`. That means, now the overridden method - here `B.show(A obj)` is called. That's it. – Seelenvirtuose Mar 24 '22 at 14:43

0 Answers0