Constructor

A constructor is a block of code similar to a method that’s called when an instance of an object is created. Here are the key differences between a constructor and a method:

check.png A constructor doesn’t have a return type.

check.png The name of the constructor must be the same as the name of the class.

check.png Unlike methods, constructors are not considered members of a class.

check.png A constructor is called automatically when a new instance of an object is created.

Here’s the basic format for coding a constructor:

public ClassName (parameter-list) [throws exception...]

{

statements...

}

The public keyword indicates that other classes can access the constructor. ClassName must be the same as the name of the class that contains the constructor. You code the parameter list the same way that you code it for a method.

Notice also that a constructor can throw exceptions if it encounters situations that it can’t recover from. For more information, see throw Statement.

A constructor allows you to provide initial values for class fields when you create the object. Suppose that you have a class named Actor that ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.