简体   繁体   English

如何仅使用构造函数的部分参数? (Java)

[英]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). 我被要求创建一种方法,以给定学生的街道编号(int)和门牌号(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: 1)创建一个像这样的构造函数:

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: 2)或者,如果您不想使用构造函数,则使用如下代码:

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

You can use null in Construction. 您可以在Construction中使用null。 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" 例如new Student(null, 5, 1)通常可以使用new Student(null, 5, 1)但是您可以使用此方法覆盖默认值,例如当名称默认为private String name = "Peter"

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

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