Constructor Examples
This page was last reviewed on Aug 29, 2023.
Dot Net Perls
Constructor. A class must be initialized. We do this with a constructor, a special initialization routine. It is a special method, with no explicit return type.
In a constructor, we use logic that sets fields and validates arguments. And with multiple constructors, we vary the arguments passed to create classes.
Two files. The Program.java file stores the main() method. And the Test.java file stores the Test class, which has a constructor. We invoke the Test constructor from main().
And In the Test constructor, we receive one integer parameter. We then assign the id field to the value received.
Info This field (id) is stored throughout the lifetime of this class. It persists in memory.
Finally We invoke the display() method on the Test class to display the value of the "id" field.
public class Program { public static void main(String[] args) { // Use Test constructor. Test test = new Test(1); // Call display method. test.display(); } }
public class Test { int id; public Test(int id) { // Store id in class memory. this.id = id; } public void display() { // Display id. System.out.println("ID is " + this.id); } }
ID is 1
Overload. We can provide overloaded constructors. We specify a different argument list for each overload. The constructors are separate, but we can provide default values for fields.
Here The first constructor for the Box class accepts only value "a." It sets value "b" to 0 as a default.
class Box { int a; int b; public Box(int a) { this.a = a; this.b = 0; } public Box(int a, int b) { this.a = a; this.b = b; } public String toString() { return "a = " + a + ", b = " + b; } } public class Program { public static void main(String[] args) { // Use one-argument constructor. Box box = new Box(1); System.out.println(box); // Use two-argument constructor. Box box2 = new Box(1, 2); System.out.println(box2); } }
a = 1, b = 0 a = 1, b = 2
Default constructor. Classes have a default constructor when no explicit constructors are present. So if we do not add a constructor, we can instantiate the class with no arguments.
class Box { public int volume; } public class Program { public static void main(String[] args) { // Create object with default constructor. Box box = new Box(); box.volume = 100; System.out.println(box.volume); } }
Private constructor. Sometimes we want to restrict access to how a class is created. We can enforce a certain creation pattern, as with a factory or singleton pattern.
Here We use a private modifier on our constructor. We add a static get() method to call the private constructor and return an instance.
Then We call Test.get() to get instances of the Test class. Special logic can enforce constraints in get().
class Test { static Test get() { // Call private constructor to make object. return new Test(); } private Test() { System.out.println("Private constructor"); } } public class Program { public static void main(String[] args) { // Get instance of Test class. Test t = Test.get(); System.out.println(t != null); } }
Private constructor true
Super constructor undefined. When a class extends a class that has only an explicit constructor, it loses its hidden "default" constructor. This program does not compile.
Note The Cat class can have no default Cat() constructor unless Animal() also has one.
Note 2 This program will compile if we uncomment both the explicit zero-argument constructors Animal() and Cat().
class Animal { // public Animal() { // // } public Animal(int size) { } } class Cat extends Animal { // public Cat() { // // } } public class Program { public static void main(String[] args) { Cat c = new Cat(); System.out.println(c != null); } }
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Implicit super constructor Animal() is undefined for default constructor. Must define an explicit constructor
This constructor. We can call a constructor with the this-keyword. Consider this program. We have a constructor for Cat with no arguments.
And The Cat constructor uses "this" to invoke another constructor with default arguments.
class Cat { int size; String color; public Cat(int size, String color) { this.size = size; this.color = color; } public Cat() { // Create a default cat with size 10 and color black. this(10, "black"); } public void display() { System.out.println("This cat is " + this.color + " and " + this.size + " pounds."); } } public class Program { public static void main(String[] args) { // Create a default cat. Cat cat = new Cat(); cat.display(); } }
This cat is black and 10 pounds.
Factory. With a factory pattern implementation, we use a method to return a new object based on a value. A factory is an abstraction for the creation of classes—it calls constructors.
Syntax. Constructors improve the syntax of object-oriented programming. We could use methods, such as initialize methods, instead of constructors.
But methods, unlike constructors, do not enforce the same rules. A constructor must be called before a class is created. A constructor is thus a safe place to initialize memory.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 29, 2023 (edit).
© 2007-2024 Sam Allen.