the dood the dood - 4 years ago 90
Java Question

Java inheritance and method resolution order

I've got the following code example:

class p {
public void druckauftrag() {
// ...

public void drucke() {

class cp extends p {
public void drucke() {

Calling the following lines:

cp colorprinter = new cp();

There is no problem understanding why "cp.druckauftrag();" results in console output "Color-Printer".

But when I call:

p drucker = (p)colorprinter;

I get the same output - why?
Does the typecast overwrite the object "drucker" 's method "drucke" with "drucke" from colorprinter?

Thanks in advance for every explanation.

Answer Source

colorprinter is an instance of cp. Even when you upcast it to p, it's drucke() method will be still the one from cp.

The difference is that after you upcast colorprinter, you will not be able to invoke the methods that cp defines on its own.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download