int或byte混淆

时间:2013-10-19 03:53:35

标签: java int byte

public class Tester {
    public Tester(){
        System.out.println("Hello");
    }

    public Tester(byte b){
        System.out.println("byte");
    }

    public Tester(int i){
        System.out.println("int");
    }

    public static void main(String[] args) {
        Tester test=new Tester(12);
    }
}

请告知为什么打印是int,我也尝试过其他整数,它们都打印为int,但是例如,1 2 3 4 5 6 7 ....这些数字也可以称为byte,对吧?那么为什么只调用int?

3 个答案:

答案 0 :(得分:5)

默认情况下,它将接受为int,除非您将其强制转换为byte

如果你想得到字节,那么按照

进行操作
Tester test=new Tester((byte)12);

输出字节

答案 1 :(得分:2)

"An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int."

因此,您的12int

接着说:“可以从int文字创建整数类型byte,short,int和long的值。”例如:

byte b = 100;
short s = 10000;

10010000始终为int。它们恰好与其他类型兼容。

答案 2 :(得分:1)

默认类型12int,因此选择int构造函数。

要调用byte构造函数,需要使用显式强制转换

  

但如果我删除:public Tester(int i){System.out.println(“int”); },   它也不会打印字节,相反,它有一个错误

如果删除int构造函数,那么编译器将无法找到任何合适的构造函数来调用,因此它将是错误的。

相关问题