0

I'm learning Java and I'm doing this exercise and I have to say what the main method prints. Its goal is to better understand Java inheritance.

interface X extends Remote{
    A m(B bb) throws RemoteException;
}

class A implements Serializable{
     int a;
     A m(A aa){ 
         aa.a = 3; 
         System.out.println("A.m"); 
         return aa;
     }
}

class B extends A{
     int b;
     A m(B bb){
        bb.b = 7; 
        System.out.println("B.m");
        return bb;
     }
}

class C extends A implements X{
    public B m(B bb){
        if(bb.b == 7) bb.b = 9; else bb.b = 1;
        System.out.println("C.m");
        return bb;
    }
}

Now I have a main method in which I call:

X x = new C();
B b = new B();
(x.m(b)).m(b);   // prints C.m() A.m()

The third line of my main method, prints "C.m() A.m()" but I don't understand why it prints A.m(). The x.m(b) returns an object that has both static and dynamic type == B; on this object it is invoked m(b) method; so why it is not called the m() method of B class?

I've seen that the m() mehtod in B class is not an overriding of the m() method in A class because they have different explicit parameter.

thanks in advance

2
  • 4
    I would start from avoiding naming things as A,a,aa, m(A aa), a.m, aa.a. It just makes code harder to read. Commented Feb 6, 2015 at 15:24
  • You are right and I totally agree with you. It's an exercise taken from a book, it's only to explore inheritance. Any ideas about why it prints C.m() A.m() instead of C.m() B.m() as I supposed? Thanks m8 Commented Feb 6, 2015 at 15:33

1 Answer 1

5

b in an instance of B, which extends A. As such, B has 2 m methods.

To know which is called, what is important is the type of the object on which the method is called.

(x.m(b))

is the result of the call to the m method from the X interface, because the declaring type of x is X.

Therefore (x.m(b)) is an object of type A (even though the actual implementation is a B).

This being a type A, the m method from the A class is called.

If you change the names of the methods, it will become clearer that the m methods from A and B are really different objects.

Your mistake is assuming that

The x.m(b) returns an object that has both static and dynamic type == B;

Which is wrong, because x is declared of type X, making the result of x.m a type A.

Sign up to request clarification or add additional context in comments.

1 Comment

another important point is that the method in B A m(B bb){ does not override the method in A A m(A aa){ because the argument is more specific, meaning it cannot answer all calls of the method in A. (But I think you already understood that part).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.