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
You can still do
to cast the reference back to type of B.
Note: the object is not altered in any way and is always a
BThe only time you need an upcast is in method selection.