關於JAVA中的方法重寫:
1、子類中的方法與父類中的方法有相同的傳回型別,相同的方法名稱,相同的參數列表
2、子類中的方法的存取層級不能低於父類中該方法的存取層級(即 方法前的修飾 private protected public 層級從低到高)
3、子類中方法拋出的異常的範圍不能大於父類中方法拋出的異常的範圍(即 子類可以不拋出異常,或者拋出的異常是父類拋出的異常的子類)
class A {
public int getLen() ...{
return 1;
}
}
public class B extends A {
public float getLen() ...{
return 2;
}
}
// 這既不是overload也不是override。 ... ...
covariance.
Covariance means that the type of arguments, return values, or exceptions of overriding methods can be subtypes of the original types.
Java
Exception covariance has been supported since the introduction of the language. Return type covariance is implemented in the Java programming language version J2SE 5.0. Parameter types have to be exactly the same (invariant) for method overriding, otherwise the method is overloaded with a parallel definition instead.
(1) override -- covariance of return value and/or exception
class Parent{
Object func(Number n) throws Exception{
...
}
}
class Child extends Parent{
String func(Number n) throws SQLException {
...
}
}
這叫做override。因為child func method的傳回值和Exception都parent funct method的傳回值和Exception的子類。
SQLException extends Exception (since first version)
String extends Object, (since J2se 5.0)
所以,這是overrider.
parent vtable
Entry 1: Object func(Number n) throws Exception of Parent
child vtable
Entry 1: String func(Number n) throws SQLException of Child
(2)overload - no support covariance of parameter type
class Parent{
Object func(Number n){
...
}
}
class Child extends Parent{
Object func(Integer i) {
...
}
}
這是overload。因為java不支援method參數類型的covariance。
parent vtable
Entry 1: Object func(Number n) of Parent
child vtable
Entry 1: Object func(Number n) of Parent
Entry 2: Object func(Integer i) of Child