简体   繁体   English

在Java中重载和重写

[英]Overloaded and overridden in Java

I know how to overload a method, and how to override a method. 我知道如何重载方法,以及如何覆盖方法。 But is that possible to overload AND override a method at the same time? 但是,是否可以同时重载和覆盖方法? If yes, please give an example. 如果是,请举个例子。

Overloading and overriding are complementary things, overloading means the same method name but different parameters, and overriding means the same method name in a subclass with the same parameters. 重载和重写是互补的,重载意味着相同的方法名称但不同的参数,并且重写意味着具有相同参数的子类中的相同方法名称。 So its not possible for overloading and overriding to happen at the same time because overloading implies different parameters. 因此,不可能同时发生重载和覆盖,因为重载意味着不同的参数。

Examples: 例子:

class A {
    public void doSth() { /// }
}

class B extends A {
    public void doSth() { /* method overriden */ }

    public void doSth(String b) { /* method overloaded */ }

}

Cheers! 干杯!

overloading and overloading are just abstractions. 重载和重载只是抽象。 Overloading just means the compiler uses the name in conjunction with the types and number of parameters for addressing what function to call. 重载只是意味着编译器将名称与参数的类型和数量结合使用来寻址要调用的函数。 In reality overloading a method is no different than naming it something different because the key the compiler uses to look up the function is a combination of name and parameter list. 实际上,重载方法与命名不同的方法没什么不同,因为编译器用来查找函数的键是名称和参数列表的组合。

Overriding is kind of the same principle except the compiler can address the overriden function with the super keyword. 除了编译器可以使用super关键字解决overriden函数之外,覆盖是一种相同的原则。

So can you override an overloaded function? 那么你可以覆盖重载函数吗? Yes, since the overloaded method is a completely different method in the eyes of the compiler. 是的,因为重载方法在编译器眼中是完全不同的方法。

It depends what you mean. 这取决于你的意思。 A method can be an override for an overloaded method in a superclass. 方法可以是超类中重载方法的覆盖。 And you can overload a method that you are simultaneously overriding using another method. 并且您可以使用其他方法重载一个同时覆盖的方法。

However, you cannot have one method that is both a new overload and an override. 但是,您不能拥有一个既是重载又重写的方法。 For a method to be an override, another method with the same signature must already exist in the superclass ... and that means that this method cannot be a new override. 对于要成为覆盖的方法,具有相同签名的另一个方法必须已存在于超类中...并且这意味着此方法不能是新的覆盖。

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

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