方法過載之引數型別的自動提公升

2021-10-03 13:25:18 字數 3180 閱讀 4312

方法過載會根據方法引數的不同而去匹配,對於基本型別資料存在自動型別提公升的情況。`

public

static

void

main

(string[

] args)

// 基本資料型別

public

static

void

test

(byte a)

public

static

void

test

(short a)

public

static

void

test

(char a)

public

static

void

test

(int a)

public

static

void

test

(long a)

public

static

void

test

(float a)

public

static

void

test

(double a)

包裝類public

static

void

test

(byte a)

public

static

void

test

(short a)

public

static

void

test

(character a)

public

static

void

test

(integer a)

public

static

void

test

(long a)

public

static

void

test

(float a)

public

static

void

test

(double a)

public

static

void

test

(object a)

以byte a = 1為例,存在如下自動提公升方式:

byte–> short–> int --> long --> float --> double --> integer -->object

2. 引用資料型別提公升,以string為例:string --> object

3. 如下輸出結果是什麼:

public

static

void

main

(string[

] args)

public

static

void

test

(double a)

public

static

void

test

(string str)

public

static

void

test

(object a)

輸出結果:the method test(object) is ambiguous for the type demo。

原因是對於null來說,會尋找最能匹配該引數的方法,double和string引用型別引數都能夠匹配。程式分辨不出到底是呼叫哪個方法。

此時,肯定會有疑問,為什麼object不和前兩者衝突?

public

static

void

main

(string[

] args)

public

static

void

test

(string str)

public

static

void

test

(object a)

輸出結果是 this is string

public

static

void

main

(string[

] args)

public

static

void

test

(double a)

public

static

void

test

(object a)

輸出結果是this is double。

如果把含有object引數的放在前面,結果怎樣的呢?

其實,結果是一樣的,含有object型別引數的方法優先順序最低。

小結:出現引用型別引數匹配時,編譯時可以通過,如果出現null值匹配,最多只能有一種除了object型別引數的方法出現,否則就報錯。object型別引數優先順序最低,沒有其他引用型別引數匹配時,才會匹配object型別引數的方法。

例題:

arraylist list =

newarraylist()

;list.

add(

123)

;list.

add(

"123");

list.

remove

(123);

system.out.

println

(list)

;

請問輸出結果什麼?

結果:indexofbound***ception。

list有乙個remove(int index)方法,而collection中有乙個remove(object obj)方法,arraylist實現了list,list繼承自collection,所以arraylist中有兩個過載方法,分別是remove(int index)和remove(object obj),list.remove(123)就是呼叫remove(int index),初始化list底層陣列長度是16,size為2,所以經過remove方法內的校驗,發現引數越界了。

方法過載的引數為基本型別

1.基本型別從乙個較小的型別自動提公升到乙個較大的型別。package example4 import org.junit.test classname primitiveoverloading author howardallen date 2018年7月29日 上午10 17 40 descri...

C中的型別自動提公升

同一句語句或表示式如果使用了多種型別的變數和常量 型別混用 c 會自動把它們轉換成同一種型別。以下是自動型別轉換的基本規則 1.在表示式中,char 和 short 型別的值,無論有符號還是無符號,都會自動轉換成 int 或者 unsigned int 如果 short 的大小和 int 一樣,un...

方法過載,傳參時,引數是主資料型別自動轉型

若我們傳到方法裡的引數的資料型別 小於 方法中使用的自變數,就會對那種 資料型別進行 轉型 處理 如果過載方法中不存在符合的自變數的話,會自動轉型為大一級的資料型別 char 獲得的效果稍有些不同,這是由於假期它沒有發現乙個準確的char 匹配,就會轉型為int。方法採用了容量更小 範圍更窄的主型別...