Java polymorphism - case study

I have some problems with the following example (more precisely, with one specific line). Here's the code (question follows):

public class Up
{
    public void cc(Up u) {System.out.println("A");}
    public void cc(Middle m) {System.out.println("B");}
}

public class Middle extends Up
{
    public void cc(Up u) {System.out.println("C");}
    public void cc(Down d) {System.out.println("D");}
}

public class Down extends Middle
{
    public void cc(Up u) {System.out.println("E");}
    public void cc(Middle m) {System.out.println("F");}
}

public class Test
{
    public static void main(String... args)
    {
        Up uu = new Up();
        Up pp = new Middle();
        Down dd = new Down();

        uu.cc(pp); // "A"
        uu.cc(dd); // "B"
        pp.cc(pp); // "C"
        pp.cc(dd); // "B"
        dd.cc(pp); // "E"
        dd.cc(dd); // "D"
    }
}

Now uu.cc(pp);they are uu.cc(dd);pretty obvious, since uu is an instance Upand pp"also looks like Up(at compile time). The most suitable method for ddis cc(Middle m)because it ddis an instance Downthat inherits from Middle.

The lines with which I have the most problems are pp.cc(dd);and dd.cc(dd). I'm really a bit confused about which method is chosen, when and how these things are determined at compilation or at runtime. I would be glad if someone helped me understand.

+3
2

, , .

, pp.cc(dd) Up.cc(Down). - Up.cc(Middle), . Up.cc(Middle), Middle . , "B".

dd.cc(dd) Down.cc(Down). : Middle.cc(Down), , Down.cc(Middle), . Middle.cc(Down). Down, "D".

15.12, 15.12.2 - .

+5

pp.cc(dd); , pp, Up. cc(Middle m). Middle, Up.

dd.cc(dd) , Down, Middle Up, dd Down. Middle cc(Down) dd .

, . .

0

Source: https://habr.com/ru/post/1794110/


All Articles