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 constructorpublic 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 valuesSystem.out.println(obj.x); // printing x}}
class Shapes {int sides;String shapeName;//defining the constructorpublic Shapes(int num, String name) {//assisgning values in the constructorsides = num;shapeName = name;}public static void main(String[] args) {Shapes shape1 = new Shapes(4, "Square"); // calling the constructor and initializing valuesSystem.out.println("A "+ shape1.shapeName + " has " + shape1.sides + " sides. ");Shapes shape2 = new Shapes(5, "Pentagon"); // calling the constructor and initializing valuesSystem.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 constructorpublic Shapes(int sides, String shapeName) {this.sides = sides; // "this" refers to the class itselfthis.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 construcorpublic 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 nullShapes 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 nullShapes shape2 = new Shapes(5, "Pentagon"); // default constructor is calledSystem.out.println("A "+ shape2.shapeName + " has " + shape2.sides + " sides. ");}}
Free Resources