Why bark method can not be called

前端 未结 5 881
醉梦人生
醉梦人生 2021-01-23 07:20
class Animal{
    void run() {
    }
}
class Dog extends Animal {
    void bark() {
    }
}
class Testing{
    public static void main(String[] args)  {
        Animal d         


        
5条回答
  •  孤独总比滥情好
    2021-01-23 07:51

    This is how its work.

    When compiler try to detect who is d.? its see.

    Animal d
    

    Compiler doesn't know know how its created, look at the reference type. So, d is an Animal.

    Now the reference is Animal. Does Animal have a bark() method? no. ERROR.

    May be d is a Dog inside but compiler doesn't know that and compiler shouldn't know, Compiler translate what you said about d in that case. That's why you getting the error.

    Now you can tell that I want d to act as Dog because I know d is a Dog by,

    ((Dog) d);
    

    and then call bark()

    ((Dog) d).bark();
    

    So compiler will take d as a Dog only for this operation.

提交回复
热议问题