java中方法override和overload的几个注意点

关于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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值