How to overload a Constructor in Java
Overview
In this tutorial, we will learn to overload constructor methods in Java with an example. We would take the Dog class as an example. We will create two constructors for the class. The default no-arg constructor and an overloaded constructor that accepts the object arguments in the parameters.
//default constructor public Dog() { this.name = "JustBorn"; this.weight = 0.1; this.height = 0.1; } // overloaded constructor public Dog(String name, double weight, double height) { this.name = name; this.weight = weight; this.height = height; }
The default constructor always creates the same object with the specified object properties in the default constructor.
In the code, we create one default Dog object and another object using the overloaded constructor.
Code Listing
package com.testingdocs.tutorial.dog; //Dog.java //www.TestingDocs.com public class Dog { private String name; private double weight; private double height; //default constructor public Dog() { this.name = "JustBorn"; this.weight = 0.1; this.height = 0.1; } // overloaded constructor public Dog(String name, double weight, double height) { this.name = name; this.weight = weight; this.height = height; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } @Override public String toString() { return "name=" + name + ", weight=" + weight + ", height=" + height ; } }
Driver
package com.testingdocs.tutorial.dog; /********************************************* * DogDriver.java * www.TestingDocs.com * *********************************************/ public class DogDriver { public static void main(String[] args) { Dog dogDefaultObject= new Dog(); Dog dogObject= new Dog("Tommy",2.5,0.75); System.out.println("Dog One=" + dogDefaultObject.toString()); System.out.println("Dog Two=" + dogObject.toString()); } }
Program Output
Dog One=name=JustBorn, weight=0.1, height=0.1
Dog Two=name=Tommy, weight=2.5, height=0.75