java面向物件程式設計---方法
阿新 • • 發佈:2022-03-18
二、方法
1、方法的過載
1.1 方法的簽名
- 方法的唯一標識就是方法的簽名:方法的名字和引數列表;
- 一個類中不能出現兩個方法的簽名完全一樣的方法
1.2 方法的過載
- 方法名相同但引數列表不同稱之為方法的過載。
public void show(){} //互相構成過載 public void show(int i) {}
1.3 訪問過載方法
- 編譯器在編譯時會根據方法的起那麼繫結呼叫不同的方法
2、構造方法
2.1 構造方法的語法結構
- 構造方法是類的成員之一----------特殊的方法,有如下兩個規則:
- 方法名和類名相同;
- 沒有返回值型別,且不寫void
publicclass Person{ public Person(){ //構造方法 } }
2.2 通過構造方法初始化成員變數
- 構造方法的意義:初始化成員變數
- 當例項化一個物件時:new Person():實際上是執行了對應的構造方法
public class Person() { Public Person() { System.out.println("執行了無參構造方法"); } } public class Test{ public void static main(String[] args){ Person p= new Person();//執行了無參構造方法 } }
2.3 this關鍵字
- this關鍵字解決了構造方法引數名稱的屬性名稱同名的問題;
public Person(String name,int age) { this.age = age; this.name = name;//this解決同名問題。增加程式碼可讀性 }
- this關鍵字是誰?誰呼叫了this.屬性或方法中的某個屬性和方法,則this就呼叫誰
public Person(String name) { System.out.println("Person的無參構造方法");this.name = name;//this.指Person物件。 }
2.4 預設的構造方法
- 一個類必須有構造方法,當類中沒有定義時,編譯器會提供一個預設的無參構造方法;
- 當我們顯式的定義了任意一個構造方法時,系統將不會提供預設的無參構造方法。
public class Person { String name; int age; public Person(String name) {//類名相同 且無返回值型別--- 構造方法 System.out.println("Person的無參構造方法"); this.name = name;//區分同名的 } public void show () { System.out.println("show1"); } public void show (int i) { System.out.println("show2"); } public void show (double d) { System.out.println("show3"); } public void show (int i ,double d) { System.out.println("show4"); } public void Show (int i ,double d) { System.out.println("show5"); } } public class TestMethod { public static void main(String[] args) { Person p = new Person();//會報錯,系統不會提供預設的構造方法 } }
2.5 構造方法的過載
- 類名相同,但引數列表不同的構造方法,我們稱之為互相構成過載。
public Person(String name,int age) { this.name = name; this.age = age; } public Person(String name) {//類名相同 且無返回值型別--- 構造方法 System.out.println("Person的無參構造方法"); this.name = name;//區分同名的 }