java中方法override和overload的幾個注意點

來源:互聯網
上載者:User

關於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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.