【发布时间】:2015-01-05 13:09:20
【问题描述】:
我有两个 Student 构造函数,我试图将它们都用于一个对象。但我应该做错了,因为我的输出不是我所期望的。
输出: 学校:无 年级:0 意向专业:null
学生的身份证号码是: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);
}
}
似乎我已经初始化了第一部分,但我得到了 null 和 0??!!!
【问题讨论】:
-
当您创建全新的第二个对象时,您在第一个对象创建中输入的信息会丢失。我的问题是你为什么要这样做?
-
无论如何,你只会初始化一半你想要的变量。有一种更好的方法可以做到这一点,但这取决于你想走哪条路;您对一个巨大的建造者感到满意,还是对建造者更开放?
-
查看this thread 了解相同的问题。
标签: java