我们可以在 Java 中更改方法签名吗?
javaobject oriented programmingprogramming更新于 2024/6/29 22:32:00
不可以,在重写超类的方法时,我们需要确保两个方法具有相同的名称、相同的参数和相同的返回类型,否则它们将被视为不同的方法。
简而言之,如果我们更改签名,则无法重写超类的方法,如果您尝试执行超类的方法。
原因 − 如果您更改签名,则两者都被视为不同的方法,并且由于超类方法的副本在子类对象中可用,因此它将被执行。
示例
class Super { void sample(int a, int b) { System.out.println("Method of the Super class"); } } public class MethodOverriding extends Super { void sample(int a, float b) { System.out.println("Method of the Sub class"); } public static void main(String args[]) { MethodOverriding obj = new MethodOverriding(); obj.sample(20, 20); } }
输出
Method of the Super class