首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java Override跟Overload

2012-12-23 
Java Override和Overloadoverride是覆写,对应于OO编程的继承特性,意思就是在子类中重写父类中的方法;???ov

Java Override和Overload

override是覆写,对应于OO编程的继承特性,意思就是在子类中重写父类中的方法;???

overload是重载,对应于OO编程的多态特性,意思就是在同一个类中同样名称的多个方法, 这多个方法之间的区别在他们的参数列不同。

?

?

===========================================

?

?

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

?

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/always_my_fault/archive/2007/11/29/1907574.aspx

?

?

?

热点排行