TLDR: I get an error when casting. I have commented the line.
I am trying to write this below program. My thoughts are as follows. I have a parent who has some debt, say a mortgage. this parent has a child who has a different form of debt (school fees.)
When I create a child, it is created with a debt object associated with it. However, I want to change the debt object to reflect the correct kind of debt the child has.
I thought that since I have made the casting explicit, I shouldn't have any issues with it. Can you explain why I am getting an error?
I have tried debugging and googling but I haven't had much luck other than needing to understand I need to explicitly cast.
public static void main(String[] args) {
Child child = new Child("Tim");
}
public class Parent {
protected String name;
protected Debt debt;
public Parent (String name){
this. name= name;
this.debt= new Debt();
}
}
public class Child extends Parent{
protected SchoolFees schoolFees;
public Child(String name) {
super(name);
schoolFees= new SchoolFees();
schoolFees= (SchoolFees) debt;//when I comment this line out, the program runs fine.
}
}
public class Debt {}
public class SchoolFees extends Debt{}
I have looked at the other stack over flow posts and see this:
class A {...}
class B extends A {...}
class C extends A {...}
**You can cast any of these things to Object, because all Java classes inherit from Object. You can cast either B or C to A, because they're both "kinds of" A. You can cast a reference to an A object to B only if the real object is a B. **
I think I am casting from B to A, which should be allowed. Let me know where I have gone wrong here.
ANSWER
You can't cast from a parent class to child class as they are not of the same type. In java, you can only cast objects of the type.