Java overloading and overriding

后端 未结 9 1617
暖寄归人
暖寄归人 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 09:07

    Method Overloading simply means providing two separate methods in a class with the same name but different arguments while method return type may or may not be different which allows us to reuse the same method name.

    But both methods are different hence can be resolved by compiler at compile time that's is why it is also known as Compile Time Polymorphism or Static Polymorphism

    Method Overriding means defining a method in the child class which is already defined in the parent class with same method signature i.e same name, arguments and return type.

    Mammal mammal = new Cat();
    System.out.println(mammal.speak());
    

    At the line mammal.speak() compiler says the speak() method of reference type Mammal is getting called, so for compiler this call is Mammal.speak().

    But at the execution time JVM knows clearly that mammal reference is holding the reference of object of Cat, so for JVM this call is Cat.speak().

    Because method call is getting resolved at runtime by JVM that's why it is also known as Runtime Polymorphism and Dynamic Method Dispatch.

    Difference Between Method Overloading and Method Overriding

    For more details, you can read Everything About Method Overloading Vs Method Overriding.

提交回复
热议问题