Java构造函数:创建一个对象,短参数被解释为int

时间:2012-09-25 03:37:07

标签: java constructor integer short

我正在用Java编写一个小的排序程序,旨在获取一个“学生”对象,并确定它的名称,职业和教室依赖于参数和属性。但是,当我尝试创建第一个对象时,问题就出现了。 到目前为止,一切都是这样的:

public class Student {
    private String name, classroom;
    /**
     * The career code is as follows, and I quote:
     * 0 - Computer Science
     * 1 - Mathematics
     * 2 - Physics
     * 3 - Biology
     */
    private short career, idNumber;

    public Student (String name, short career, short idNumber){
        this.name = name;
        this.classroom = "none";
        this.career = career;
        this.idNumber  = idNumber;
    }

    public static void main(String args[]){
        Student Andreiy = new Student("Andreiy",0,0);
    }
}

错误在对象创建行上出现,因为在构造函数调用short时,它坚持将0,0解释为整数,从而导致不匹配问题。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

一种方法是使用强制转换器告诉编译器该值为short

Student Andreiy = new Student("Andreiy",(short)0,(short)0);

或者,重新定义Student课程以接受int而不是short。 (对于职业代码,我建议使用enum。)

答案 1 :(得分:0)

您应该将Integer转换为short。短转换的整数需要缩小,因此需要显式转换。只要你有内存限制,就应该在java中使用整数。

public Student (String name, Career career, int idNumber)

//Enumeration for Career so no additional checks are required.
 enum Career
 {
     Computer_Science(0),Mathematics(1),Physics(2),Biology(3);
     private Career(int code)
     {
         this.code = code;
     }
     int code ;

     public int getCode()
     {
         return code;
     }

 }

然后你可以做类似下面的事情

new Student("Andreiy", Career.Computer_Science, 0);