Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Java Inheritance

Given the following Java code:

class mainul {

    public static void main(String[] args) {
        
    /*block 1*/
        B b1 = new B();
        A a1 = b1;
        a1.m1(b1);
        
    /*block 2*/
        B b2 = new B();
        B a2 = b2;
        b2.m1(a2);
    }
}

class A {

    public static void p(Object o) {
        System.out.println(o.toString());
    }

    public void m1(A a) {
        p("m1(A) in A");

    }
}

class B extends A {

    public void m1(B b) {
        p("m1(B) in B");
    }
}

Can someone shed some light to why the output of this program is

m1(A) in A
m1(B) in B

One would expect the output of block 1 to be "m1(B) in B" due to the fact the dynamic type of a1 is B. I noticed that the function signatures in A and B for m1 do not match (one expects an object of type A and the other of B as its argument), and the method in A seems to get priority, but I can't really link this to my output as it doesn't seem to be consistent with the output of block 2.

like image 678
almost smart Avatar asked Jul 01 '26 18:07

almost smart


1 Answers

As you noticed, B.m1(B) does not override A.m1(A), as they take different arguments (try adding the @Override annotation and you'll see the compiler complain). So so it can never be called via a reference to an A.

It can, however, be called via a reference to a B.

like image 150
Oliver Charlesworth Avatar answered Jul 04 '26 08:07

Oliver Charlesworth