0

以下代碼在方法重載方面是正確的。重載方法:自動數據類型轉換

public class class7A { 
    public static void main(String[] args) { 
    testing obj_1 = new testing(); 
    int a=12,b=14,c=20; 
    obj_1.func1(a,b,c); //invokes the 3rd method in the testing class 
             } 
         } 

class testing{ 
void func1(int a,int b){ 
    System.out.println("The values of length and breadth entered for the box is "+a+" "+b); 
         } 
void func1(int a){ 
    System.out.println("We can only talk about length here folks which is "+a); 
       } 
void func1(double a,double b,double c){ //This method is invoked 
    System.out.println("The value of length ,breadth and height is "+a+","+b+","+c+" respectively"); 
             } 
      } 

現在的事實,當第三方法定義的參數是「雙重」的第三個方法調用,即使給出的解釋是,Java的自動轉換的雙轉換成int也這兒過得知道Java沒有任何操作通過首先將類型轉換爲後端的int類型,對於字節也是如此。 但是,當我將第三種方法的參數更改爲字節類型而不是雙倍時,代碼會給出錯誤。例如,下面的代碼給出了一個錯誤:

爲什麼會發生這種情況?

public class class7A { 
    public static void main(String[] args) { 
    testing obj_1 = new testing(); 
    int a=12,b=14,c=20; 
    obj_1.func1(a,b,c); 
             } 
         } 

class testing{ 
void func1(int a,int b){ 
    System.out.println("The values of length and breadth entered for the box is "+a+" "+b); 
         } 
void func1(int a){ 
    System.out.println("We can only talk about length here folks which is "+a); 
       } 
void func1(byte a,byte b,byte c){ //This gives error 
    System.out.println("The value of length ,breadth and height is "+a+","+b+","+c+" respectively"); 
+0

* 「java自動將double轉換爲int」*否,它不會 – Tom

+0

@Tom,如果它不能解釋,爲什麼int參數對於定義爲「double」類型的參數有效? –

+0

只要看看___你自己的代碼。爲什麼要將double轉換爲int,int是源類型還是目標類型的兩倍?沒有意義向後轉換。 – Tom

回答

0

當您作爲方法的參數傳遞時,您必須將數據類型int轉換爲字節。

例如:

public class class7A { 
    public static void main(String[] args) { 
     testing obj_1 = new testing(); 
     int a = 12, b = 14, c = 20; 

     obj_1.func1((byte) a, (byte) b, (byte) c); 
    } 
} 

class testing { 
    void func1(int a, int b) { 
     System.out.println("The values of length and breadth entered for the box is " + a + " " + b); 
    } 

    void func1(int a) { 
     System.out.println("We can only talk about length here folks which is " + a); 
    } 

    void func1(byte a, byte b, byte c) { // This gives error 
     System.out.println("The value of length ,breadth and height is " + a + "," + b + "," + c + " respectively"); 
    } 
} 

,如果你想使其他類型的轉換,你可以檢查這個職位,其中解釋更詳細的如何從int轉換爲字節

https://stackoverflow.com/a/842900/7179674