JAVA - 函數重載和重寫__LINUX

來源:互聯網
上載者:User

1. 函數重載(OverLoding)

概念:同名函數具有不同的參數列表。

作用:實現單個類內部的多態性,是靜態多態。

注意點: 

(1) 參數類型、個數、順序至少有一個不相同。

(2) 不能通過存取權限傳回型別拋出的異常進行重載。

2. 函數重寫(OverRideing)

概念:在子類中定義某個方法與其父類有相同的名稱和參數;子類對象引用或者子類對象的父類引用使用這個方法時,將調用子類中的定義。

作用:在繼承中實現多態性,是父類與子類之間多態性的表現。

注意點:

(1) 方法名、參數、傳回值必須相同。

(2) 子類方法不能縮小父類方法的存取權限。

(3) 子類方法不能拋出比父類更多的異常(子類可以不拋出異常)。

(4) 被定義為final的方法不能被重寫。

3判斷對象引用能否調用一個方法的原則

(1) 向上轉型:子類轉型成父類型。

(2) 子類對象引用:方法存在子類定義中則可以調用,否則不可以調用。

(3) 父類對象引用:方法存在父類定義中則可以調用,調用結果根據多態性原則;否則不可以調用。

// Animal類

public class Animal {

public void introduce(){

System.out.println("I am an animal!");

}

}  

// Cat類

public class Cat extends Animal {

//重寫了父類的introduce,實現了overriding

public void introduce(){

System.out.println("I am a cat!");

}

//實現了Overloading

public void introduce(String name){

System.out.println("I am a cat, My name is : " + name); 

}

}

// Dog類

public class Dog extends Animal {

//重寫了父類的introduce,實現了overriding

public void introduce(){

System.out.println("I am a dog!");

}

//實現了Overloading

public void introduce(String name){

System.out.println("I am a dog, My name is : " + name);

}

}

// 測試類別

public class Test {

    public static void main(String[] args) {

//Overriding是父類與子類之間多態性的一個表現

Animal animal1 = new Animal();

Animal animal2 = new Cat();

Animal animal3 = new Dog();

animal1.introduce();

animal2.introduce();

animal3.introduce();

// animal2.introduce("JACK");  是錯誤的用法

// animal3.introduce("JACK");  是錯誤的用法

//Overloading是在一個類中多態性的體現

Cat cat = new Cat();

cat.introduce();

cat.introduce("JACK");

}

}


運行結果如下:

I am an animal!

I am a cat!

I am a dog!

I am a cat!

I am a cat, My name is : JACK

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.