简体   繁体   中英

Is there any better way to create an object?

I'm creating a new object from class Student, however, class Student contains an object from class Address and class Address contains an object from class PostCode. I tried to create 3 different objects, is there any better way to do this?

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();

class Student

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;
}

class Address

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;
}

class PostCode

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;
}

i also tried

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

Both seem perfectly valid ways to create new objects. In your second version, you forgot new keyword before Address and PostCode. Otherwise there is really no difference in terms of validity. What you might find is that in the second implementation, you may be going over 80 characters. It is a convention to keep lines short, usually under 80 characters.

In order to print the values of your objects, implementing a print function as you suggested is a valid option but in Java, the convention is to implement a toString() method in every class which returns the values as a string. For example, in your PostCode class, it should look something like

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

And then, you can print the values by

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

If you values are not of the type String, eg they could be int eg studentid, you can say something like

return Integer.toString(studentid);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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