【问题标题】:Is there any better way to create an object?有没有更好的方法来创建一个对象?
【发布时间】:2019-03-31 09:28:19
【问题描述】:

我正在从 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");

【问题讨论】:

  • 按照你的方式创建它们有什么问题?
  • 我觉得这不是一种有效的方法。因为我需要为一个学生创建 3 个对象

标签: java object constructor


【解决方案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());

如果您的值不是字符串类型,例如他们可以是int,例如studentid,你可以这样说

return Integer.toString(studentid);

【讨论】:

    【解决方案2】:

    只需使用多级继承的概念...在类的2中使用超级方法并将参数传递给超级...通过这样做,您只需创建一个对象并将所有参数传递给构造函数那个班的

    【讨论】:

      猜你喜欢
      • 2010-09-10
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      相关资源
      最近更新 更多