简体   繁体   中英

Inheriting Java super class and Type Casting

I have two Classes in Java

Class A { void method1(){} }
Class B extends A {  void method2(){} }

When I run the following it works fine:

Class C {
  public static void main(String [] args){
    A a1  = new A();
    A a2 = new B();
    B b1 = new B();
    ((B)a2).method2();
  }
 }

but why the following does not work ?

Class C {
  public static void main(String [] args){
    A a1  = new A();
    A a2 = new B();
    B b1 = new B();
    (B)a2.method2();
  }
 }

Thanks

You have to call the method after casting. You need brackets around a2 ie

((B)a2).method2();

Like Kabir said, you need to first cast the object before calling a method from another object.

It is because Java reads your second statement as: (B) (a2.method2();)

So java tries to use method two in the A object a2, but it can't because there is no method2() in that object.

However, when you type cast it (By putting (B) before a2 in parenthesis), it reads it like:

(Turn a2 into B).method2();

Which runs fine because it is turning a2 into a B, which includes method 2, beforehand.

In an easy comparison with a math concept, it is like the order of operations on how you calculate values. You wouldn't say 5 + 5 * 2 = 20 , you would say 5 + 5 * 2 = 15 , because it first calculates 5 * 2 , then adds 5 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM