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() {
// ...
drucke();
}

public void drucke() {
System.out.println("B/W-Printer");
}
}

class cp extends p {
public void drucke() {
System.out.println("Color-Printer");
}
}


Calling the following lines:

cp colorprinter = new cp();
cp.druckauftrag();


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

But when I call:

p drucker = (p)colorprinter;
drucker.druckauftrag();


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