【发布时间】: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