Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit Type Conversion of sub class object to super class in java

Consider below code:

public class Test{
  public static void main(String str[]){
     B b = new B();
     A a1 = (A)b;//Explicit type conversion
     A a2 = b;
  }
}
class A{}
class B extends A{}

In the above code are the two line:

A a1 = (A)b;//Explicit type conversion
A a2 = b;

Equivalent? If not then what is the difference between the two and if yes then is there any scenario in java where we need to explicitly convert a sub class object into a super class object?

like image 427
Ankur Avatar asked Oct 11 '12 16:10

Ankur


1 Answers

The explicit type casting of the reference, not the object) is redundant and some IDEs will suggest you drop it.

If you do

A a1 = (A)b;

You can still do

B b2 = (B) A;

to cast the reference back to type of B.

Note: the object is not altered in any way and is always a B

there is no scenario in java where you would need it?

The only time you need an upcast is in method selection.

void method(Object o) { }

void method(String s) { }

method("hello");          // calls method(String)
method((Object) "hello"); // calls method(Object)
like image 190
Peter Lawrey Avatar answered Sep 28 '22 00:09

Peter Lawrey