Constructing Objects

When you define a class, you can define one or more constructors for it. A constructor provides a way of creating (constructing) an instance of its class.

When you use the new keyword to create an object, you are calling the constructor of that class whose argument list matches the arguments provided in the call.

The following code calls the default (no-arg) constructor for the JButton class:

JButton btnSave = new JButton();

Constructors are special methods that must match the names of the classes in which they are defined, and which have no return type. They are used to control how objects are created, and often, to initialize fields to the values specified in the argument list.

When you run the preceding code, the runtime ...

Get Java Garage 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.