Gandalf StormCrow
Gandalf StormCrow

Reputation: 26222

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 ?

Upvotes: 6

Views: 182

Answers (3)

Tim
Tim

Reputation: 20777

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.

Upvotes: 10

sutlermb
sutlermb

Reputation: 115

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.

Upvotes: 1

Omry Yadan
Omry Yadan

Reputation: 33706

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.

Upvotes: 1

Related Questions