简体   繁体   中英

Question about Java class constructor

Can somebody tell me what does this mean? I'm going trough Java book and I've encontered this example :

public class Message {

    Message(){}

    public Message(String text){
        this.text = text;
    }

What does Message(){} Mean ?

It's a package private empty constructor taking no arguments.

You can use it to create a new Message instance from any code in the same package, by using new Message(); .

It's worthwhile to know it will not initialize the text field, which will therefore hold the default null value.

just like

Message()
{
}

but using less lines.

the access level for it is the (default) package access level meaning only classes within the same package can instantiate this object using this constructor.

The class Message defines two constructors. The first (the default constructor) is scoped to package-level visability. That means that only classes within the same package can execute code that looks like:

Message msg = new Message();

All classes outside of the package must call the second constructor.

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