Say Person
is base class.
Doctor
class extends Person
.
Now suppose diagnose()
is method which belongs to Doctor
class.
Person p = New Person();
Doctor q = (Doctor)p;
q.diagnose();
Why would this throw error?
q
is object reference of kind Doctor
. All objects of class share same copy of methods, so diagnose()
should be available to q
.
There are no fields of methods which would be available to p
would not be available in Doctor
.
Why would java not allow this?
Why would this throw error?
Because you're casting an object of type Person
to Doctor
. The value of p
is a reference to an instance of Person
, not to an instance of Doctor
, therefore the cast fails.
If you had:
Person p = new Doctor();
Doctor d = (Doctor) p;
d.diagnose();
then it would be fine.
This isn't a matter of what's visible - d.diagnose()
is visible whenever d
is a variable of type Doctor
, as it is here. It's a matter of execution-time casting in the line before the diagnose()
call.
See more on this question at Stackoverflow