Calling overloaded inherited methods using super class reference

后端 未结 10 1280
既然无缘
既然无缘 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:34

    Java chooses the most specific applicable type. In this case m1(int) is not applicable. Emphasis on the reference of class that hold object of same class(c1) or an object of any sub classes of class(c2) & method name and parameter list .

    Your method with double parameters is being called because double takes priority over int. This is because an int can be assigned to a double, but not the other way around.

    So there are so many things to be consider at the (run) time of method call.

    Yes for ur case your main class should be like this

            public static void main(String[] args) {
                C1 c = new C2();
                c.m1(10);
                ((C2) c).m1(10);
        //or
                C2 cobj = new C2();
                cobj.m1(10);
            }
    
    
    **OutPut**
    Inside C1.m1(): 10.0
    Inside C2.m1(): 10
    Inside C2.m1(): 10
    

提交回复
热议问题