简体   繁体   中英

How do I use only portion of parameters of constructors? (Java)

I was asked to create an method to add student to an array given their street number(int) and house number(int). Here's an example of what I'm talking about.

  Student a = new Student("Abigail", 1, 5);

I'm only allowed to use student's street number and house number, which is only a portion of the parameters of constructor. Is there any way to relate object(Student) just from portion of information?

Here's my constructor:

 public Student(String n, int sN, int hN){
        name = n;
        streetNum = sN;
        houseNum = hN;
    }

You can create another constructor with less parameters like this:

public class Student {

    public static final String DEFAULT_NAME = "Cookie Monster";
    public static final String DEFAULT_STREET_NUMBER = 46; //Sesame Street Number?   

    private String name;
    private int streetNum;
    private int houseNum;

    public Student(String n, int sN, int hN){
        name = n;
        streetNum = sN;
        houseNum = hN;
    }

    public Student(int sN, int hN){
        this(DEFAULT_NAME, sN, hN);
    }

    public Student(int hN){
        this(DEFAULT_STREET_NUMBER, hN);
    }
}  

i think there is two way:

1) Create a constructor like this:

public Student(int sN, int hN){
        streetNum = sN;
        houseNum = hN;
    }

And use it like :

  Student a = new Student(1, 5);

2) Or if you don't want to a constructor then use like:

  Student a = new Student("", 1, 5);

You can use null in Construction. For example new Student(null, 5, 1) generally this is possible but you overwrite defaults with this method like when the name defaults to private String name = "Peter"

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