class Animal{
void run() {
}
}
class Dog extends Animal {
void bark() {
}
}
class Testing{
public static void main(String[] args) {
Animal d
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.
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();
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
.
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
You can use explicit cast to call it
((Dog)d).bark();