问题描述
以下代码打破了OO原则?不是Java OO原则,而是一般OO原则。
What OO principle is broken by the following code ? Not Java OO principle but general OO principle.
class GeneralArg{}
class Arg extends GeneralArg{}
class A{
public void test(Arg a){}
}
class B extends A{
@Override
public void test(GeneralArg a){}
}
我认为这应该有效!
但是有一个编译错误,说 B.test()
不会覆盖 A .test()
However there is a compile error saying that B.test()
doesn't override A.test()
推荐答案
你正在做的不是覆盖而是重载。
What you are doing is not overriding but overloading.
更改参数列表时重载方法。
您在更改实现时覆盖方法。
You overload a method when you change the parameter list.You override a method when you change it implementation.
public class Foo {
public void method1() {
}
public void method1(String str) {
//We overload method1
}
}
public class Bar extends Foo {
public void method1(String str) {
// We override method1 here
}
public void method1(Number num) {
// We overload method1 here
}
}
注意,那个注释它不是强制性的,它只通知编译器您已覆盖某些方法以防止潜在的故障。
Note, that annotation is not mandatory it only inform the compiler that you have override some method to prevent potential faults.
当您在子类声明方法中使用相同的[签名]覆盖它时,当您添加/删除切换参数顺序时,您会重载。这个规则服从Java世界,因为每个非最终方法都是虚拟的,可以被覆盖。
Concluding when you in child class declare method with the same [signature] you override it, when you add/remove switch parameter order you overload. This rule obey to Java world as every not final method is virtual an can be overridden.
这篇关于Java中重写方法的更宽泛的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!