Construction. Constructors

[comp1110-7C]

A constructor is a class member that is used to initialise objects of a class when they are created. By default, every class has a parameterless constructor that does nothing, and for a class named MyClass, can be called using:

new MyClass()

You can define your own constructors. As soon as you do, the default parameterless constructor does not exist anymore. Constructors are special because, unlike normal methods, they do not have a name or return type. In Java, you specify them using the class type, as in:

class MyClass { /** * An empty, parameterless constructor for MyClass */ MyClass() { } }
bars magnifying-glass caret-down plus minus arrow-right xmark