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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With