Java overloading and overriding

后端 未结 9 1630
暖寄归人
暖寄归人 2020-11-29 08:16

We always say that method overloading is static polymorphism and overriding is runtime polymorphism. What exactly do we mean by static here? Is the call to a method resolved

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 08:55

    Method overloading means making multiple versions of a function based on the inputs. For example:

    public Double doSomething(Double x) { ... }
    public Object doSomething(Object y) { ... }
    

    The choice of which method to call is made at compile time. For example:

    Double obj1 = new Double();
    doSomething(obj1); // calls the Double version
    
    Object obj2 = new Object();
    doSomething(obj2); // calls the Object version
    
    Object obj3 = new Double();
    doSomething(obj3); // calls the Object version because the compilers see the 
                       // type as Object
                       // This makes more sense when you consider something like
    
    public void myMethod(Object o) {
      doSomething(o);
    }
    myMethod(new Double(5));
    // inside the call to myMethod, it sees only that it has an Object
    // it can't tell that it's a Double at compile time
    

    Method Overriding means defining a new version of the method by a subclass of the original

    class Parent {
      public void myMethod() { ... }
    }
    class Child extends Parent {
      @Override
      public void myMethod() { ... }
    }
    
    Parent p = new Parent();
    p.myMethod(); // calls Parent's myMethod
    
    Child c = new Child();
    c.myMethod(); // calls Child's myMethod
    
    Parent pc = new Child();
    pc.myMethod(); // call's Child's myMethod because the type is checked at runtime
                   // rather than compile time
    

    I hope that helps

提交回复
热议问题