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.