I have a class "Child" which extends class "Parent", and class Child doesn't even have a single function or variable.
I created object for each and tried to cast parent object to child object. But I'm getting "java.lang.ClassCastException: deepJava.Downcasting cannot be cast to deepJava.ExtendedClass" Exception. I tried using "instanceOf" based on the suggestions from other blog and forums and its returning false. Technically there is no difference between Parent and Child object right? Why I'm getting false for "instanceOf".
public class Parent { public String testString; int i = 8; public void simpleFunction() { System.out.println(i); } } class Child extends Parent { } class testDowncasting { public static void main(String[] args) { Parent downCast = new Parent(); downCast.simpleFunction(); Child chClass = new Child(); chClass = (Child) downCast; } }
In my scenario, I don't have write access to the "Parent" class. Hench I need to play inside "Child" class only.
And is there any workaround like calling each get methods from "Parent" class dynamically and set those in "Child" class dynamically?
Thank you.
--- Update ---
Soon after posting this question, I tried the below code and it's working.
Parent downCast = new Child(); downCast.simpleFunction(); Child chClass = new Child(); chClass = (Child) downCast; chClass.simpleFunction();
But its not working if I set "parent" variables and assign that to "downCast", which is the crucial part, and later try to cast to Child.
Parent downCast = new Child(); Parent parentObj = new Parent(); parentObj.setTestString("Test 1"); downCast = parentObj; Child chClass = new Child(); chClass = (Child) downCast; System.out.println(chClass.getTestString());
Is there any work around for "Downcasting"?
Thank you.