+ 1
What can be its some practical use cases in Java ?
Can you wise java developers , please tell me some practical and logical use cases of casting an object of subclass to its superclass type . And also why referencing an object of subclass to its superclass (like Person obj = new Programmer() where Programmer extends Person class) can still be useful even if we can't use the fields and methods of its subclass by doing this . Please clear my doubt where such kind of type casting can really be useful .
2 Answers
+ 1
in future you can decide to use SoftwareEngineer instead Programmer, and if you use only Person methods this change is easy. (but I don't like this strategy too)
upcasting is useful by method arguments and return type, then method can work with more types (all subtypes)
+ 1
here it is necessary
import java.util.*;
public class MyClass {
public static void main(String args[]) {
/*java.util.ImmutableCollections.Map1<String,String> m =
Map.of("aa","bb"); //error */
Map<String,String> map =
Map.of("aa","bb");
System.out.println( map.getClass() );
map = Map.of("aa","bb","cc","dd");
System.out.println( map.getClass() );
}
}