我有兩個構造函數爲學生,我正試圖使用一個對象他們兩個。但我應該做錯了,因爲我的輸出不是我所期望的。使用多個構造函數與Java中的一個對象
輸出: 學校:空 年級:0 意向科目:空
學生的身份證號碼是:154324 學生姓名:山姆灣 學生的GPA:3.56
代碼的類定義:主
public class Student
{
private int id, gradeLevel;
private String name, school, major;
private double gpa;
//constructor to initialize the instance variables of student object
public Student(int id, String name, double gpa)
{
this.id = id;
this.name = name;
this.gpa = gpa;
}
public Student(int gradeLevel, String school, String major)
{
this.gradeLevel = gradeLevel;
this.school = school;
this.major = major;
}
//toString() to display the attributions of the student object
public String toString()
{
return "School: " + school +
"\nGrade Level: " + gradeLevel +
"\nIntended Major: " + major + "\n" +
"\nStudent's ID number is: " + id +
"\nStudent's name: " + name +
"\nStudent's GPA: " + gpa;
}
}//end class
代碼:
public class StudentDrive
{
public static void main(String [] args)
{
//creating student objects
Student sam = new Student(12, "Alpha High School", "Biology");
sam = new Student(154324, "Sam Bay", 3.56);
System.out.println(sam);
}
}
看來我已經初始化了第一部分,但我得到空和0 ?? !!!
當你創建一個全新的第二個對象在第一個對象創建輸入的信息丟失。我的問題是你爲什麼要這樣做? – csmckelvey 2014-11-08 23:44:27
無論如何,你只會初始化你想要的一半變量。這樣做有一個更好的方法,但這取決於你想要走哪條路;你對一個巨大的構造函數感到滿意嗎,還是對構建者更開放? – Makoto 2014-11-08 23:45:21
請參閱[此主題](http://stackoverflow.com/questions/18999635/how-to-execute-multiple-constructor-when-creating-single-object)相同的問題。 – mattias 2014-11-08 23:46:12