Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why subclass reference can't hold superclass object in java

Tags:

java

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.

like image 914
Lucky Avatar asked Aug 27 '15 10:08

Lucky


3 Answers

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.

like image 110
Raedwald Avatar answered Nov 15 '22 09:11

Raedwald


Every Child is a Parent but not every Parent is a Child. Rule of Inheritance.

like image 29
Suresh Atta Avatar answered Nov 15 '22 10:11

Suresh Atta


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.

like image 35
Shaibal S Avatar answered Nov 15 '22 08:11

Shaibal S