重载方法:自动数据类型转换

时间:2017-04-20 17:41:30

标签: java type-conversion overloading

以下代码对于方法重载是正确的。

  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");
                                      }
             }

现在给出的解释是,即使为第3个方法定义的参数是“double”,也会调用第3个方法,这就是java在这里自动将double转换为int。我也知道java对基元类型进行任何操作首先将类型转换为后端的int,这也适用于字节。 但是,当我将第3个方法的参数更改为字节类型而不是double时,代码会给出错误.Foe示例下面的代码会给出错误:

为什么会这样?

  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");

1 个答案:

答案 0 :(得分:0)

当您作为方法的参数传递时,必须将数据类型int转换为byte。

示例:

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转换为byte

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