class One{
}
class Two extends One{
}
class Main{
public static void main(String[] args){
Two t = new One(); // invalid
}`
}
I a
Every Child is a Parent but not every Parent is a Child. Rule of Inheritance.
The type of TWO cannot be an instance of ONE because there are members and methods that TWO has which ONE doesn't have. However, The type of ONE can reference TWO because TWO has everything that ONE has.
For example, if ONE can WALK and TWO can also RUN, then if you have an object from the type ONE then is needs to be able to WALK. So if ONE references TWO that works because TWO can walk.
But when you have an object of type TWO then it needs to be able to RUN so you cannot reference it to ONE which cannot RUN.
Consider class Two contain a method, let say demo().
class One{
}
class Two extends One {
void demo(){
System.out.println("in Two");
}
}
class Main{
public static void main(String[] args){
Two t = new One(); // Suppose this is valid at compilation time
t.demo();
}
}
Now suppose if compiler doesn't give us error when we create object of class One i.e. child reference holds object of parent. Further t is reference of class Two, hence t.demo() is valid.
Now when program runs, reference t contains object of class One. When program reaches t.demo() then t contains object of class One and class One does not have any method named demo().
So to prevent such type of errors compiler checks if object is type of reference i.e. object class is same as reference class or child of reference class.
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.
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.