Calling overloaded inherited methods using super class reference

后端 未结 10 1285
既然无缘
既然无缘 2020-12-29 07:38

I do not understand this Java behavior. I have two classes:

class C1 {
    public void m1(double num) {
        System.out.println(\"Inside C1.m1(): \" + num         


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 08:43

    The reason why you see the output as Inside C1.m1(): 10.0 and not Inside C1.m1(): 10 or Inside C2.m1(): 10.0 is because :

    1. You are not overriding the method m1 in C2. You are overloading the m1(doube) method that you inherited from C1 to m1(int) instead.
    2. The C2 class now has two m1 methods. One that is inherited from C1 and has the signature m1(double) and one that is overloaded in C2 and has the signature m1(int)
    3. When the compiler sees the call c.m1(10), it resolves this call based on the reference type. Since the reference type is C1, the compiler is going to resolve this call to m1(double) in C1.
    4. At runtime, the JVM is going to resolve the call to m1(double) in C2 which is the method inherited from C1. (As explained in point 2)

    There are two ways in which the m1(int) method can be called :

    ((C2)c).m1(10);

    OR

    C2 c = new C2(); c.m1(10);

提交回复
热议问题