我们可以在 Java 中覆盖时更改方法签名吗?
否,覆盖父类的某个方法时,我们要确保两个方法具有相同的名称、相同参数以及相同返回类型,否则它们会被视作不同的方法。
简而言之,如果我们更改签名,那么你将不能覆盖父类的方法,如果你尝试,则将执行父类的方法。
原因 - 如果更改签名,那么两者会被视为不同的方法,且由于父类方法的副本可用在子类对象中,所以该副本会执行。
示例
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP