6

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 ?

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think it would be interesting to add the fact that the good point is that no one can use the default constructor outside of the class, so the user is forced to give the text parameter
@Valentin: Nope, that's private your thinking about.. This is package-private (also known as default), which is accessible anywhere from the same package.
my bad, seems like I'm not really awake today :/
1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.