2
class Animal{
    void run() {
    }
}
class Dog extends Animal {
    void bark() {
    }
}
class Testing{
    public static void main(String[] args)  {
        Animal d = new Dog();
        d.run();
        d.bark();
    }
}

I am trying to call bark method using object of dog class whose reference is stored in Animal class variable. But it is showing me compile time error. Can anyone explain Why?

steven35
  • 3,747
  • 3
  • 34
  • 48

5 Answers5

3

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.

Saif
  • 6,804
  • 8
  • 40
  • 61
  • then what is the advantage of using Animal d = new Dog()? Isn't better to just use Dog d = new Dog()? – nSv23 Feb 13 '20 at 00:07
1

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();
thomas.mc.work
  • 6,404
  • 2
  • 26
  • 41
0

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.

Dragondraikk
  • 1,659
  • 11
  • 21
0

You can use explicit cast to call it

((Dog)d).bark();
steven35
  • 3,747
  • 3
  • 34
  • 48
  • You should explain why your code will work so the op will learn – nicopico Jun 01 '15 at 13:33
  • I did say explicit cast, it's thoroughly explained in the java docs. – steven35 Jun 01 '15 at 13:34
  • 1
    Looking at the op question, it is clear he did not fully understand the concepts of inheritance and polymorphism. Giving a technical, one-line solution is not going to help him much in this regard. – nicopico Jun 01 '15 at 13:41
0

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

Community
  • 1
  • 1
Azzy
  • 1,717
  • 2
  • 13
  • 17