why subclass reference can't hold superclass object in java

后端 未结 5 438
醉梦人生
醉梦人生 2021-01-19 03:14
class One{

}
class Two extends One{

}
class Main{

      public static void main(String[]  args){
       Two t = new One(); // invalid 

}`
}

I a

5条回答
  •  礼貌的吻别
    2021-01-19 03:59

    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.

提交回复
热议问题