简体   繁体   English

函数重载是通过 Java 中的运行时多态实现的。 Java 还支持运算符重载吗?

[英]Is function overloading achieved through run-time polymorphism in Java. Also is operator overloading supported by Java?

Generally function overloading is achieved through run-time polymorphism in languages,but is the case in Java opposite?一般语言中的函数重载是通过运行时多态来实现的,但是Java中的情况正好相反吗? Because Oracle document says unless function is declared static ,it is loaded at run-time.因为 Oracle 文档说除非函数被声明为静态,否则它会在运行时加载。 So if a function is not loaded at compile time, then how can overloading occur?那么如果一个函数在编译时没有加载,那么重载怎么会发生呢?

In the case of function Overloading, it is static (compile-time) polymorphism because the compiler knows which method is to be called based on the number and type of parameters.在函数重载的情况下,它是静态(编译时)多态性,因为编译器根据参数的数量和类型知道要调用哪个方法。 For example:例如:

public class FunctionOverloadingTest {
    public void display(String first) {
        System.out.println("I have one parameter");
    }

    public void display(String first, String second) {
        System.out.println("I have two parameters");
    }

    public static void main(String[] args) {
        FunctionOverloadingTest functionOverloadingTest= new FunctionOverloadingTest();
        functionOverloadingTest.display("one");
    }
}

In this case, compiler decides which display method is to be called based on the number of parameter passed in the function call.在这种情况下,编译器根据函数调用中传递的参数数量决定调用哪个显示方法

No. Method overloading is compile time polymorphism.不。方法重载是编译时多态性。

In simple terms we can say that a class can have more than one methods with same name but with different number of arguments or different types of arguments or both.简单来说,我们可以说一个类可以有多个具有相同名称但具有不同数量的参数或不同类型的参数或两者兼有的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM