0

In the following code, can someone explain to me the meaning of "A ba = (A)b;" and explain to me the outputs and how they are derived.

class A {
    public void f(A a) { System.out.println("fa(A)");}
    public void f(B b) { System.out.println("fa(B)");}
}

class B extends A {
    public void f(A a) { System.out.println("fb(A)"); }
    public void f(B b) { System.out.println("fb(B)"); } 
}

public class TypeMeister {
    public static void main(String[] args){
        A a = new A();
        B b = new B();
        A ba = (A)b; //please explain

        a.f(a);
        a.f(b);
        b.f(a);
        b.f(b);
        a.f(ba);
        b.f(ba);;
        ba.f(a);
        ba.f(b);
        ba.f(ba);
    }
}

Thanks for your help.

cs95
  • 379,657
  • 97
  • 704
  • 746
G.B
  • 37
  • 6
  • 1
    You're casting it to type `A`. – Andrew Li Jun 04 '17 at 19:26
  • 1
    `A ba = (A)b;` is a type cast. With this, you change a value's static type. – Turing85 Jun 04 '17 at 19:28
  • But, then wouldn't the output of ba.f(a) be fa(A). But, when I print it, I get fb(A) – G.B Jun 04 '17 at 19:30
  • 1
    No. You only change the STATIC type. Instanc-methods, however, are bound by the dynamic (actual) type at runtime. – Turing85 Jun 04 '17 at 19:31
  • Note that in `A ba = (A)b;` the cast `(A)` is redundant because widening reference conversions are implicitly allowed with assignment. `A ba = b;` would do the same. – Radiodef Jun 04 '17 at 19:33
  • Thanks - I got it! – G.B Jun 04 '17 at 19:38
  • Answer in the duplicate link is a bit long-winded, but explains the difference between method selection at compile-time vs method selection at run-time, which is what your question is really about. – Andreas Jun 04 '17 at 19:43
  • Go through this SO question to understand how casting work: https://stackoverflow.com/questions/20096297/explicit-type-casting-example-in-java – Sadiq Ali Jun 04 '17 at 19:48

1 Answers1

0

A ba = (A)b; Is an explicit type cast operation. b is explicitly of type B, but implicitly of type A, since B is a subclass of A.

Since B is a subclass of A, you can initialise object b as so:

A b = new B(); 

This is equivalent to

B b = new B();
A ba = (A)b;

...but 1 line shorter.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • That does not answer the acutal question of what `A ba = (A)b;` does. – Turing85 Jun 04 '17 at 19:29
  • @Turing85 I was getting to that. :-) – cs95 Jun 04 '17 at 19:31
  • *"The compiler would know during compile time that method `f` belongs to class `B`."* This is not actually true because there could be a 3rd class `class C extends B {...}` which overrides the method `f`. Instance methods are always virtual unless they're `private`. – Radiodef Jun 04 '17 at 19:35
  • @Radiodef Oh, I see. Thanks for that info. Have edited my post. – cs95 Jun 04 '17 at 19:38