How to use constructors in Java
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}}
Rules for writing a Java constructor
- The constructor name must have the same name as the class name.
- The constructor does not have a return type and only returns the current class instance.
- Access modifiers can be used in the constructor declaration to control its access by other classes.
- The user can have as many parameters as they want.
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;}}
Default constructors
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