Writing and overloading constructors¶
โ Java 17 ยท Building Objects the Right Way with Constructors ยท 1/3
Anatomy of a constructor¶
public class Movie {
private String title;
public Movie(String t) {
title = t;
}
}
// somewhere else
Movie m = new Movie("Dune");
- Its name is exactly the class name, capital letter included.
- It has no return type, not even
void. newreserves memory, then calls the constructor whose parameters match the arguments.- Parameters can be of any type, except
var.
Lookalikes that aren't constructors¶
public class Movie {
public movie() { } // โ wrong case: a method with no return type โ doesn't compile
public void Movie() { } // โ ๏ธ a valid method, never called by new
public Movie(var t) { } // โ var isn't allowed for parameters
}
A return type, even void, turns a "constructor" into an ordinary method.
Several ways to build a movie¶
A class can declare several constructors, each with a different list of parameter types. This is constructor overloading:
public Movie() { title = "Untitled"; }
public Movie(String title) { this.title = title; }
public Movie(String title, int minutes) { /* โฆ */ }
public Movie(String title, String... genres) { /* โฆ */ }
new Movie(); // runs the first one
new Movie("Dune", 155); // runs the third one
As with methods, each signature must be unique: two constructors can't have the same list of parameter types. The arguments of new decide which one runs.
The constructor Java writes for you¶
When a class declares no constructor at all, the compiler adds a default constructor: no parameters, empty body.
public class Clip { } // gets a default constructor
public class Teaser { public Teaser() { } } // declares its own: no default added
public class Poster { public Poster(boolean hd) { } }
public class Banner { private Banner() { } }
| Class | new X() from another class |
|---|---|
Clip |
โ the default constructor |
Teaser |
โ its own no-argument constructor |
Poster |
โ it has a constructor, so no default one |
Banner |
โ its only constructor is private |
A private constructor prevents other classes from creating instances at all.
With several constructors, the same assignments tend to repeat. The next page shows how one constructor reuses another, and how a child builds its parent first.