Why bark method can not be called

前端 未结 5 842
醉梦人生
醉梦人生 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.

    0 讨论(0)
  • 2021-01-23 07:51

    It's because you store your dog in the variable of type Animal which is only able to run(). There could be another animal Cat which isn't able to bark().

    If you want to let the dog bark() then you need to put in a Dog typed variable:

    Dog rolf = new Dog();
    rolf.bark();
    
    0 讨论(0)
  • 2021-01-23 07:52

    You have declared d as an Animal.

    However, while internally d may be a Dog, being stored as an Animal will only allow you to use methods declared in Animal.

    0 讨论(0)
  • 2021-01-23 08:06

    You can call only the methods defined in the reference type. i.e since the Animal class has only one method ( run() ) you cant call bark() on it, even if its referring to Dog object.

    What you are doing is upcasting, you can get to know more about upcasting and downcasting here

    0 讨论(0)
  • 2021-01-23 08:07

    You can use explicit cast to call it

    ((Dog)d).bark();
    
    0 讨论(0)
提交回复
热议问题