简体   繁体   中英

Java constructor

如何定义单个构造函数public packet(String[] biscuit) ,这会使我的字段从private String[] biscuitList变为private String[] biscuit

Just assign it to the field.

public class Packet {
    private String[] biscuitList;
    public Packet(String[] biscuit) {
        this.biscuitList = biscuit;
    }
}

The this refers to the current Packet instance (which you just created using new Packet ). The this.biscuitList refers to the biscuitList field of the current Packet instance. The = biscuit assigns the given biscuit to the left hand (which in this case is the biscuitList field.

That said, a String[] variable shouldn't really be called with a name ending in List . This may cause ambiguity with a List<String> . You can just call it biscuit , or maybe better, biscuits .

public class Packet {
    private String[] biscuits;
    public Packet(String[] biscuits) {
        this.biscuits= biscuits;
    }
}

Also, classnames and constructor names ought to start with uppercase. Ie Packet and not packet .

To learn more about Java, check the Trials Covering the Basics .

this.biscuitList = biscuit;

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