有没有更好的方法来创建对象?

时间:2019-03-31 09:28:20

标签: java object constructor

我正在从Student类创建一个新对象,但是,Student类包含一个来自Address类的对象,而Address类包含一个来自PostCode类的对象。我尝试创建3个不同的对象,还有什么更好的方法吗?

public class Main{


public static void main(String[] args) {

    PostCode p1 = new PostCode("Keiraville", "Wollongong", "NSW");
    Address a1 = new Address (17, "Dalas",p1 , "Australia");
    Student s1 = new Student("Huang", 314531, a1, "Csit121");

    s1.print();

班级学生

public class Student {
String name;
int studentID;
Address address;
String courseID;

public Student(String name, int studentID, Address address, String courseID)
{
    this.name = name;
    this.studentID = studentID;
    this.address = address;
    this.courseID = courseID;
}

课程地址

public class Address  {
int streetNumber;
String streetName;
PostCode postCode;
String country;

public Address(int streetNum, String name, PostCode postCode, String country)
{
    this.streetNumber = streetNum;
    this.streetName = name;
    this.postCode = postCode;
    this.country = country;
}

邮政编码类

public class PostCode{
String suburb;
String city;
String state;

public PostCode (String suburb, String city, String state)
{
    this.suburb = suburb;
    this.city = city;
    this.state = state;
}

我也尝试过

Student s1 = new Student("Huang", 314531, Address(17, "Dalas", PostCode("Keiraville", "Wollongong", "NSW") , "Australia"), "Csit121");

2 个答案:

答案 0 :(得分:1)

这两个似乎都是创建新对象的完全有效的方法。在第二个版本中,您在地址和邮政编码之前忘记了new关键字。否则,在有效性方面确实没有任何区别。您可能会发现,在第二种实现中,您可能要超过80个字符。惯例是使行短,通常少于80个字符。

为了打印对象的值,按照您的建议实现打印功能是有效的选择,但是在Java中,约定是在每个类中实现一个toString()方法,该方法将值作为字符串返回。例如,在您的PostCode类中,它应类似于

public String toString() {
    return " Suburb = " + this.suburb + " City = " + this.city + " State = " this.state;
}

然后,您可以通过

打印值
PostCode postCodeObject = new PostCode("Bla", "Bla2", "Bla3");
System.out.println(postCodeObject.toString());

如果您的值不是字符串类型,例如他们可能是诠释的学生号,你可以说

return Integer.toString(studentid);

答案 1 :(得分:0)

只需使用多级继承的概念...在类nd的2中使用super方法将参数传递给super ...这样,您只需使一个对象nd将所有参数传递给构造函数该类的人