Java Constructor: Overloaded, Default, This Constructors

These Java examples use constructors on custom classes. A constructor initializes a class and may receive arguments.
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().

Test: In the Test constructor, we receive one integer parameter. We then assign the id field to the value received.

Field: 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.

Java program that calls constructor, Program.java public class Program { public static void main(String[] args) { // Use Test constructor. Test test = new Test(1); // Call display method. test.display(); } } Constructor declaration, Test.java: Java 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); } } Output 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.

Java program that overloads constructors 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); } } Output 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.
Java program that uses default constructor 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); } } Output 100
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.

Static Method

Then: We call Test.get() to get instances of the Test class. Special logic can enforce constraints in get().

Java program that uses private constructor 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); } } Output 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.

Problem: The Cat class can have no default Cat() constructor unless Animal() also has one.

Solution: This program will compile if we uncomment both the explicit zero-argument constructors Animal() and Cat().

Java program that causes compilation error 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); } } Output 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.This

And: The Cat constructor uses "this" to invoke another constructor with default arguments.

Java program that uses this constructor 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(); } } Output 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.Factory Pattern
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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls