Java Constructors
A constructor is a special method that runs when an object is created. It sets the starting values of the new object.
A constructor runs at creation
The Dog constructor stores Buddy in the name field. The print line reads the field after creation, and the stored name appears.
class Dog {
String name;
Dog() {
name = "Buddy";
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println(dog.name);
}
}A parameter constructor fills the fields
The values Ada and 36 travel with the creation call. The constructor stores each value in its field.
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person("Ada", 36);
System.out.println(person.name);
System.out.println(person.age);
}
}Two objects, two sets of values
Each creation call passes its own values. Each object keeps the values from its own call.
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
Person first = new Person("Ada", 36);
Person second = new Person("Ben", 24);
System.out.println(first.name + ", " + first.age);
System.out.println(second.name + ", " + second.age);
}
}Example
class Book {
String title;
int pages;
Book(String t, int p) {
title = t;
pages = p;
}
}
public class Main {
public static void main(String[] args) {
Book first = new Book("Dune", 412);
Book second = new Book("Emma", 474);
System.out.println(first.title + ", " + first.pages + " pages");
System.out.println(second.title + ", " + second.pages + " pages");
}
}Key points
- A constructor carries the same name as its class.
- A constructor has no return type.
- A constructor runs once for each new object.
- Values passed at creation land in the constructor parameters.
- A constructor can store parameter values in fields.
In this example, the Book constructor takes a title and a page count. Each creation call passes its own pair of values to the constructor. The prints show Dune with 412 pages and Emma with 474 pages.
Note
A class with no written constructor still builds objects, because Java supplies a simple one.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What name does a constructor carry?