1. 程式人生 > 其它 >面向物件程式設計----方法的過載(包含構造方法)

面向物件程式設計----方法的過載(包含構造方法)

過載overload

方法的過載是指一個類中可以定義有相同的名字,但引數不同的多個方法呼叫時,會根據不同的引數表選擇對應的方法。

兩同三不同

--同一個類,同一個方法名。

--不同:引數列表不同(型別,個數,順序不同)

只有返回值不同,不構成方法的過載.

Int a (String:str()),

Void a(String i),

呼叫:a()

誰能告訴我是調那個方法?

只有形參的名稱不同,不構成方法的過載

與普通方法一樣,構造方法也可以過載

package cn.Test.oop;
/**
* 測試過載
* @author 神奇的夢
*
*兩同三不同
--同一個類,同一個方法名。
--不同:引數列表不同(型別,個數,順序不同)


*/
public class TestOverload {
// 這樣不會有歧義,因為這裡呼叫時用new TestOverload(),
int x,y;
public static void main(String[] args) {
// 構建一個MyMath物件
MyMath m = new MyMath();
// 給方法中區域性變數加上實參
MyMath mx = new MyMath(1,6);
// 方法的過載是指一個類中可以定義有相同的名字,
// 但引數不同的多個方法。呼叫時,會根據不同的引數表選擇對應的方法。
  }
}
// DDK是Device Development Kit,裝置開發包的意思。
// 如果你想開發一個裝置驅動程式,如顯示卡驅動程式,就必須使用DDK。

//不要叫Math,不然就衝突了,會有歧義
//在公共類(public修飾的類)裡面寫了一個Math在調ddk裡面的Math調起來就很麻煩了
//也可以調,指定包名 儘量別重

//MyMath可以幹嘛呢!可以算數
class MyMath{
int a=22;
int b=99;
// 構造方法
public MyMath() {
System.out.print(this.a+"三"+this.b);
}

// 構造方法不能過載 不行 因為初始化時,分不清初始化a還是初始化b了
// public MyMath(int xx) {
// this.ba指的是class MyMath類裡面的int b,
// 而賦值號後面的xx指的是構造方法形參裡面的int xx


// this.b=xx;
// }
public MyMath(int xx,int yy) {
// this.a指的是class MyMath類裡面的int a,
// 而賦值號後面的xx指的是構造方法形參(區域性引數)裡面的int xx
// this.b指的是class MyMath類裡面的int b,
// 而賦值號後面的yy指的是構造方法形參(區域性引數)裡面的int yy
this.a=xx;
this.b=yy;
System.out.print(this.a+"三克油"+this.b);
}
// 在這裡我們提供這幾個方法
// 對兩個數做加法

// public double add(int b,double a) {
// return a+b;
// }


/* 形參型別不匹配,報錯,不構成過載
public int add(int c,double d) {
return (int)(a+b);
}
*/
// Type mismatch: cannot convert from double to int
// 型別不匹配: 無法從 double 轉換為 int
// 遭遇型別提升問題double+int結果時double需強制轉型
/*
public int add(int a,double b) {
return a+b;
}*/

/**/
// 返回值不同不構成過載
// 當實參傳遞為int型別時,new它會報錯
// public double add(double b,double a) {
// return (int)(a+b);
// }
// 返回值不同不構成過載
// public double add(int b,double a) {
// return a+b;
// }
// 過載方式:順序不同
public int add(int b,double a) {
return (int)(a+b);
}

// 過載方式:型別不同
public int add(double a,int b) {
return (int)(a+b);
}

// 過載方式:數量不同
public int add(int a,int b) {
return (int)(a+b);
}

public int add(int a,int b,int c) {
return a+b+c;
}
}

package cn.Test.oop;

class Studentr {
private String name ;
private int age;
public Studentr() {
System.out.println("這是預設的構造方法");
}

public Studentr(String name) {
this.name = name;
}

public Studentr(int age) {
this.age = age;
}

public Studentr(String name, int age) {
this.age = age;
this.name = name;
}

public void show() {
System.out.println("name: "+name+"----age: "+age);
  }
}

class ConstructDemo {
public static void main(String[] args) {
//Student s = new Student();
//System.out.println(s);
Studentr s0 = new Studentr();
Studentr s1 = new Studentr("劉軻");
s1.show();
Studentr s2 = new Studentr(30);
s2.show();
Studentr s3 = new Studentr("劉軻",30);
s3.show();
  }
}