简体   繁体   English

Java构造函数

[英]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 ). this是指当前 Packet实例(您刚刚使用new Packet创建的实例)。 The this.biscuitList refers to the biscuitList field of the current Packet instance. this.biscuitList引用当前Packet实例的biscuitList字段。 The = biscuit assigns the given biscuit to the left hand (which in this case is the biscuitList field. = biscuit分配给biscuit左手(在这种情况下是biscuitList字段。

That said, a String[] variable shouldn't really be called with a name ending in List . 就是说,实际上不应该使用以List结尾的名称来调用String[]变量。 This may cause ambiguity with a List<String> . 这可能导致与List<String>产生歧义。 You can just call it biscuit , or maybe better, biscuits . 您可以称其为biscuit ,或者更好的是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 . Packet而不是packet

To learn more about Java, check the Trials Covering the Basics . 要了解有关Java的更多信息,请查看涵盖基础知识试用版

this.biscuitList = biscuit;

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

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