A constructor is used to initialize objects in Java. It is called when an object of a class, using the new()
keyword, is created and can be used to set initial values to the data members of that same class.
Below is an example for using a constructor:
class MyClass { int x; // defining the constructor public MyClass(int y) { x = y; // setting the value of x equal to the passed parameter } public static void main(String[] args) { MyClass obj = new MyClass(24); //using the constructor to initialize values System.out.println(obj.x); // printing x } }
class Shapes { int sides; String shapeName; //defining the constructor public Shapes(int num, String name) { //assisgning values in the constructor sides = num; shapeName = name; } public static void main(String[] args) { Shapes shape1 = new Shapes(4, "Square"); // calling the constructor and initializing values System.out.println("A "+ shape1.shapeName + " has " + shape1.sides + " sides. "); Shapes shape2 = new Shapes(5, "Pentagon"); // calling the constructor and initializing values System.out.println("A "+ shape2.shapeName + " has " + shape2.sides + " sides. "); } }
For simplicity, it is a popular practice to give a parameter the same name as the member it is being assigned to. In such a case, the this
keyword can be used to differentiate between the parameter and the member:
class Shapes { int sides; String shapeName; //defining the constructor public Shapes(int sides, String shapeName) { this.sides = sides; // "this" refers to the class itself this.shapeName = shapeName; } }
All classes have default constructors. If the user does not create a class constructor, Java creates one. Values of the data members will be set to 0
or null
in this case since the user is not able to set the initial values for the data members of the class object.
See the code below that uses default constructors:
class Shapes { int sides; String shapeName; //defining the construcor public Shapes(int num, String name) { // values not initliazed } public static void main(String[] args) { //default contructor is called so the values are set to 0 and null Shapes shape1 = new Shapes(4, "Square"); System.out.println("A "+ shape1.shapeName + " has " + shape1.sides + " sides. "); //default contructor is called so the values are set to 0 and null Shapes shape2 = new Shapes(5, "Pentagon"); // default constructor is called System.out.println("A "+ shape2.shapeName + " has " + shape2.sides + " sides. "); } }
RELATED TAGS
View all Courses