why subclass reference can't hold superclass object in java

后端 未结 5 434
醉梦人生
醉梦人生 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:36

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

    0 讨论(0)
  • 2021-01-19 03:37

    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.

    0 讨论(0)
  • 2021-01-19 03:39

    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.

    0 讨论(0)
  • 2021-01-19 03:44

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题