Java 重载和覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2469767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:20:29  来源:igfitidea点击:

Java overloading and overriding

javaoverridingoverloading

提问by Padmanabh

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 on compiling the code? So whats the difference between normal method call and calling a final method? Which one is linked at compile time?

我们总是说方法重载是静态多态,覆盖是运行时多态。这里的静态究竟是什么意思?对方法的调用是否在编译代码时解决?那么普通方法调用和调用最终方法有什么区别呢?哪个是在编译时链接的?

回答by RHSeeger

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

我希望有帮助

回答by Bozho

Your are right - calls to overloaded methods are realized at compile time. That's why it is static.

您是对的 - 对重载方法的调用是在编译时实现的。这就是为什么它是静态的

Calls to overridden methods are realized at run-time, based on the type on which the method is invoked.

根据调用方法的类型,在运行时实现对覆盖方法的调用。

On virtual methods wikipedia says:

关于虚拟方法维基百科说:

In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final are non-virtual.

在 Java 中,所有非静态方法默认都是“虚函数”。只有用关键字 final 标记的方法是非虚拟的。

finalmethods cannot be overridden, so they are realized statically.

final方法不能被覆盖,所以它们是静态实现的。

Imagine the method:

想象一下方法:

public String analyze(Interface i) {
     i.analyze();
     return i.getAnalysisDetails();
}

The compiler can't overload this method for all implementations of Interfacethat can possibly be passed to it.

对于Interface可能传递给它的所有实现,编译器不能重载此方法。

回答by Rachel

I don't think you can call overloading any sort of polymorphism. Overloaded methods are linked at compile time, which kind of precludes calling it polymorphism.

我认为您不能将重载称为任何类型的多态性。重载的方法在编译时链接,这排除了将其称为多态的可能性。

Polymorphism refers to the dynamic binding of a method to its call when you use a base class reference for a derived class object. Overriding methods is how you implement this polymorphic behaviour.

多态是指当您使用派生类对象的基类引用时,方法与其调用的动态绑定。覆盖方法是您实现这种多态行为的方式。

回答by Naresh Joshi

Method Overloadingsimply 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 Polymorphismor Static Polymorphism

但是这两种方法是不同的,因此可以在编译时由编译器解析,这就是为什么它也被称为编译时多态静态多态

Method Overridingmeans 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 Mammalis getting called, so for compiler this call is Mammal.speak().

在这一行mammal.speak()编译器说speak()引用类型的方法Mammal被调用,所以对于编译器这个调用是Mammal.speak().

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

但是在执行的时候 JVM 清楚地知道mammal引用是持有对象的引用Cat,所以对于 JVM 这个调用是Cat.speak().

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

因为方法调用在运行时由 JVM 解析,这就是为什么它也被称为运行时多态动态方法调度

Difference Between Method Overloading and Method Overriding

方法重载和方法覆盖的区别

Difference Between Method Overloading and Method Overriding

方法重载和方法覆盖的区别

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

有关更多详细信息,您可以阅读关于方法重载与方法覆盖的一切

回答by subhashis

i agree with rachel, because in K&B book it is directly mentioned that overloading does not belong to polymorphismin chapter 2(object orientation). But in lots of places i found that overloading means static polymorphism because it is compile time and overriding means dynamic polymorphism because it s run time.

我同意 rachel 的观点,因为在 K&B 书中,在第 2 章(面向对象)中直接提到了重载不属于多态性。但是在很多地方我发现重载意味着静态多态,因为它是编译时,而覆盖意味着动态多态,因为它是运行时。

But one interesting thing is in a C++ book (Object-Oriented Programming in C++ - Robert Lafore) it is also directly mentioned that overloading means static polymorphism. But one more thing is there java and c++ both are two different programing languages and they have different object manipulation techniques so may be polymorphism differs in c++ and java ?

但是一件有趣的事情是在一本 C++ 书中(C++ 中的面向对象编程 - Robert Lafore)也直接提到了重载意味着静态多态性。但还有一件事是 java 和 c++ 都是两种不同的编程语言,它们具有不同的对象操作技术,所以 c++ 和 java 中的多态性可能不同吗?

回答by Hisham Muneer

Simple Definition - Method overloading deals with the notion of having two or more methods(functions) in the same class with the same name but different arguments.

简单定义 - 方法重载处理在同一个类中具有两个或多个名称相同但参数不同的方法(函数)的概念。

While Method overriding means having two methods with the same arguments, but different implementation. One of them would exist in the Parent class (Base Class) while another will be in the derived class(Child Class).@Override annotation is required for this.

虽然方法覆盖意味着具有两个具有相同参数但实现不同的方法。其中一个将存在于父类(基类)中,而另一个将存在于派生类(子类)中。为此需要@Override 批注。

Check this : Click here for a detailed example

检查这个: 单击此处查看详细示例

回答by Jaichander

PropertyOver-loading Overriding

属性重载覆盖

Method Names -------------->must be Same----------------must be same

方法名称 --------------> 必须相同----------------必须相同

Arg Types------------------>must be Different(at least arg)

Arg 类型-------------------> 必须不同(至少是 arg)

Method Signature

方法签名

Return Type

返回类型

Private,Static,Final

私人,静态,最终

Access Modifier

访问修饰符

try/Catch

试着抓

Method Resolution

方法解析

回答by Avnish kumar

First, I want to discuss Run-time/Dynamic polymorphism and Compile-time/static polymorphism.

首先,我想讨论运行时/动态多态和编译时/静态多态。

Compile-time/static polymorphism:- as its name suggests that it bind the function call to its appropriate Function at compile time. That means the compiler exactly know which function call associated to which function. Function overloading is an example of compile time polymorphism.

编译时/静态多态性:- 顾名思义,它在编译时将函数调用绑定到其适当的函数。这意味着编译器确切地知道哪个函数调用与哪个函数关联。函数重载是编译时多态的一个例子。

Run-time/Dynamic polymorphism:-In this type of polymorphism compiler don't know which functions call associates to which function until the run of the program. Eg. function overriding.

运行时/动态多态:-在这种类型的多态中,编译器在程序运行之前不知道哪些函数调用关联到哪个函数。例如。功能覆盖。

NOW, what are the function overriding and function overloading???

现在,什么是函数覆盖和函数重载???

Function Overloading:- same function name but different function signature/parameter.

函数重载:- 相同的函数名称但不同的函数签名/参数。

eg. Area(no. of parameter) 
        {     -------------
           ----------------
             return area;}

         area of square requires  only one parameter
         area of rectangle requires two parameters(Length and breadth)

function overriding:- alter the work of a function which is present in both the Superclass and Child class. eg. name() in superclass prints "hello Rahul" but after overring in child class it prints "hello Akshit"

函数覆盖:- 改变存在于超类和子类中的函数的工作。例如。超类中的 name() 打印“hello Rahul”但在子类中覆盖后打印“hello Akshit”

回答by Ankit Sharma

Tried to cover all differences

试图涵盖所有差异

                       Overloading                          Overriding

Method Name            Must be same                         Must be same

Argument Types         Must be same                         Must be different


Return Type            No restriction                       Must be same till 1.4V 
                                                            but after 1.4V 
                                                            co- variants 
                                                            were introduced

private/static/final   Can be overloaded                    Cannot be overridden

Access Modifiers       No restriction                       Cannot reduce the scope

Throws keyword         No restriction                       If child class method 
                                                            throws a checked 
                                                            exception the parent 
                                                            class method must throw 
                                                            the same or the  
                                                            parent exception

Method Resolution      Taken care by compiler               Taken care by JVM based 
                       based on reference types             on run-time object

Known as               Compile-Time Polymorphism,           RunTime Polymorphism, 
                       Static Polymorphism, or              dynamic polymorphism,
                       early binding                        late binding.