Java 重载和覆盖

发布于 2024-08-25 19:06:58 字数 97 浏览 3 评论 0原文

我们总是说方法重载是静态多态,重写是运行时多态。这里的静态到底是什么意思?对方法的调用是否在编译代码时解析?那么普通方法调用和调用final方法有什么区别呢?编译时链接的是哪一个?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

远山浅 2024-09-01 19:06:58

方法重载意味着根据输入创建函数的多个版本。例如:

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

在编译时选择调用哪个方法。例如:

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

方法重写意味着通过原始方法的子类定义该方法的新版本

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

我希望有帮助

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

倾城°AllureLove 2024-09-01 19:06:58

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

对重写方法的调用是在运行时根据调用该方法的类型实现的。

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

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

final 方法无法被重写,因此它们是静态实现的。

想象一下这个方法:

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

编译器无法为可能传递给它的所有 Interface 实现重载此方法。

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.

final methods cannot be overridden, so they are realized statically.

Imagine the method:

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

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

小草泠泠 2024-09-01 19:06:58

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

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

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.

月光色 2024-09-01 19:06:58

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

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

i agree with rachel, because in K&B book it is directly mentioned that overloading does not belong to polymorphism in 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.

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 ?

年少掌心 2024-09-01 19:06:58

方法重载只是意味着在一个类中提供两个具有相同名称但不同参数的单独方法,而方法返回类型可能不同也可能不同,这允许我们重用相同的方法名称。

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

方法重写 表示在子类中定义一个方法,该方法已在父类中定义,具有相同的方法签名,即相同的名称、参数和返回类型。

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

mammal.speak() 行,编译器表示正在调用引用类型 Mammalspeak() 方法,因此对于编译器来说,此调用是Mammal.speak()

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

因为方法调用是在运行时由 JVM 解析的,所以它也被称为运行时多态性动态方法分派

方法重载和方法重写的区别

方法重载与方法重写的区别

详细内容可以阅读关于方法重载与方法覆盖的所有内容

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

Difference Between Method Overloading and Method Overriding

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

︶葆Ⅱㄣ 2024-09-01 19:06:58

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

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

检查一下:
单击此处查看详细示例

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.

Check this :
Click here for a detailed example

独行侠 2024-09-01 19:06:58

属性重载覆盖

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

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

方法签名

返回类型

Private,Static,Final

访问修饰符

try/Catch

方法解析

Property Over-loading Overriding

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

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

Method Signature

Return Type

Private,Static,Final

Access Modifier

try/Catch

Method Resolution

从此见与不见 2024-09-01 19:06:58

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

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

运行时/动态多态性:-在这种类型的多态性中,编译器在程序运行之前不知道哪些函数调用与哪个函数相关联。例如。函数重写。

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

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

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

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

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

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"

清醇 2024-09-01 19:06:58

试图涵盖所有差异

                       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.

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文