why can not access child fields using parent reference

后端 未结 6 1866
耶瑟儿~
耶瑟儿~ 2021-01-22 06:03
class A {
    int super_var = 1;
}

class B extends A {
    int sub_var = 2;
}

public class Demo{
    public static void main(String []args){        
        A a = new          


        
6条回答
  •  误落风尘
    2021-01-22 06:22

    Let's say you have these classes:

    public class Animal() {
        // ...
    }
    
    public class Fish extends Animal() {
        public void swim() {...}
    }
    

    If you declared an Animal:

    Animal x = new Fish();
    

    and you called the swim() method

    x.swim();
    

    Would you expect it to work? I don't think so, because not every animal can swim. That's why you have to explicitly specify that the animal x is a Fish:

    ((Fish) x).swim();
    

    In your case, if you wanted to call that method, you should specify (technically, it's called cast) the type:

    System.out.print(((B)a).sub_var);
    

    Note:

    • This works similar for methods and variables. I used a method in the example since it's more illustrative.

    Edit:

    Let's see this example:

    Animal x;
    
    if (some_condition)
        x = new Fish();
    else
        x = new Cat();
    
    x.swim();
    

    This restriction exists, because Java won't know if, at execution time, the object assigned to x will have the method swim(). So to avoid this, you have to cast to the respective type to call a method that doesn't exist in superclass.

提交回复
热议问题