I'm trying to clarify this so I fully understand type casting. Please correct me on anything that is incorrect as I've been self learning java for about 2 months now at a really slow pace.
Let's say I created a class called SubObject. And I am aware that all classes that do not have a direct explicit superclass, are assumed to be subclasses of Object class.
Object obj1 = new SubObject();
SubObject subObj1 = (SubObject) obj1;
System.out.println(subObj1); //prints out com.examplePackage.SubObject1234e1234;
So I have successfully downcasted the reference of the base class (Object) to its derived class (subObject). However...
Object obj2 = new Object();
SubObject subObj2 = (SubObject) obj2;//this throws the ClassCastException error.
My understanding of ClassCastException error is that it's inherited RuntimeException to catch it during compile time, to show that the code has attempted to cast an object to a subclass of which it is not an instance. Because subObj2 is NOT an instance of SubObject, but rather Object, it is incompatible.
So I have 2 questions: 1. Is there any flaw/error in my understanding? 2. In which situation is downcasting actually used? Thanks for the help everyone.