Java inheritance and method parsing order

I have the following code example:

class p {
    public void druckauftrag() {
        // ...
        drucke();
    }

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

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

Call the following line:

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

Understand why "CP. druckauftrag();" no problem. Causes the console to output "color printer"

But when I called:

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

I get the same output – why? Does the type conversion overwrite the method "Drucker" of the object "Drucker" with the "Drucker" of the color printer?

Thank you in advance for every explanation

Solution

Colorprinter is an instance of CP Even if you convert it up to P, its Drucker () method is still the method from CP

The difference is that after upcast colorprinter, you will not be able to call CP's own defined methods

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>