class One{
}
class Two extends One{
}
class Main{
public static void main(String[] args){
Two t = new One(); // invalid
}`
}
I am not able to understand the reason behind it, why child class reference could not hold the object of parent, while superclass reference can hold the object of subclass.
Because a dog has all the behaviours of an animal, but something that is only known to be an animal is not guaranteed to have all the behaviours of a dog.
Every Child is a Parent but not every Parent is a Child. Rule of Inheritance.
If we think in terms of set theory, compared to the parent class, the child class is a super set. The child class has all possible properties and methods, compared to the parent class.
So, a parent class object can refer to its child class object, as the child class object includes the parent's methods and properties. Thinking vice versa, since a parent class object does not have all the methods and properties needed by a child class, a child class object cannot refer to a parent class object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With