繁体   English   中英

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

[英]Is there any better way to create an object?

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

两者似乎都是创建新对象的完全有效的方法。 在第二个版本中,您忘记了Address和PostCode之前的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());

如果您的值不是String类型,例如,它们可以是int类型,例如Studentid,则可以说类似

return Integer.toString(studentid);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM