【问题标题】:Overloading method :Automatic data type conversion重载方式:自动数据类型转换
【发布时间】:2017-04-20 17:41:30
【问题描述】:

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

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

现在对第三个方法被调用这一事实的解释是,即使为第三个方法定义的参数是“double”,java 在这里自动将 double 转换为 int。我也知道 java 对原始类型进行任何操作通过首先在后端将类型转换为 int ,这对于字节也是如此。 但是,当我将第 3 种方法的参数更改为字节类型而不是双精度时,代码会出错。例如,下面的代码会出错:

为什么会这样?

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

【问题讨论】:

  • "这里java自动把double转成int"不,不会
  • @Tom ,如果不能解释,为什么 int 参数适用于定义为“double”类型的参数?
  • 看看你自己的代码。当 int 是源类型而 double 是目标类型时,为什么要将 double 转换为 int?向后转换没有意义。

标签: java type-conversion overloading


【解决方案1】:

当您作为方法的参数传递时,您必须将数据类型 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

【讨论】:

    猜你喜欢
    • 2012-02-26
    • 2014-01-16
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    相关资源
    最近更新 更多