Java Constructor: Still, now we have discussed the basic topics of core Java tutorial. Now we are going to learn new thing like in the last post we have learned about the continuing statement. In this post, we are going to learn about a Java constructor also how to create and use the constructor with the help of some simple and easy examples.
What is Constructor in Java?
The constructor is also a block of code which is much similar to a method but not an actual method because it is used to initialise the newly created objects. It will be called automatically when an instance of a class is created, and memory is allocated for that object.
The need for Constructor
We know that when we are creating a class, the classes have some class variables & methods. So when we are creating an object of that class that time, the variables have some values. So constructor is used to assigning values to the class variables at the time of object creation. It may be done by the programmer or by Java itself (Default Constructor).
How to Define a Constructor in Java
There are some predefined rules which we need to follow at the time of creating constructor, that are:
- The constructor name should be same as the class name.
- The constructor must have no explicit return type
- A Java Constructor cannot be an abstract, static, final and synchronised.
Let’s take a simple Java program example and try to understand how a Java constructor is declared. In the below, you can see there a simple MyClass java class with a single constructor
public class MyClass { public MyClass() { } }
In the above example:
public MyClass() { }
In the above case, MyClass() Is a constructor, from that, the first Public part is an access modifier. It is the same meaning as for the methods and variables. By this, we determine what classes can access the constructor.
The second part is the name of the constructor, which is MyClass and that also the class name. Using the class name for the constructor gives a signal to the java compiler that it is a constructor. If you have noticed, then you can find that there is no return type like methods.
The third part of Java constructor is the list of parameter a constructor can take. We can define the parameter inside the (). in the above declaration; you can see that we have not mentioned any parameters. Still, later, we will see the examples of how to define parameters for a constructor.
The Fourth part is the body part of a constructor which we can define inside the brackets {}. in the above example we have not defined the body for the constructor that’s why such type of constructor is called “empty” constructor.
How does constructor work?
If we take the above example for knowing how a constructor works, let’s create an object of that class like below
MyClass obj = new MyClass();
When we create an object like that, then it internally invokes the constructor to initialise the newly created object. you may be a little bit confused regarding how it initialises let’s take another example to know a better way:
public class Hello { String name; //Constructor Hello() { name = "www.softwaretestingo.com"; } public static void main(String[] args) { Hello obj = new Hello(); System.out.println(obj.name); } }
In the above example, we are creating an object by using the new keyword, like below
Hello obj=new Hello();
When the Java compiler executes the above statement, it calls the constructor to initialise the variables or members. After complete the execution of constructor again, the flow comes back to the main method for executing the rest of the statements.
Types Of Constructors
In Java, we have mainly three types of constructor:
- Default Constructor
- No-arg Constructor
- Parameterized Constructor
Default Constructor In Java
It is not compulsory to provide a constructor in a class. If we are not providing or mentioned any constructor in a class, then the java provides a default constructor to us for the use. Let’s take a simple Java program to understand where a default constructor is used since we are not mentioned any constructor.
public class Data { public static void main(String[] args) { Data d = new Data(); } }
ImportPoint Of Default Constructor
- The main role of default constructor is to initialise the object and return the execution flow to the calling code.
- When there is no constructor defined in the class, then a default constructor is provided by the java compiler and its always without any argument.
No-args Constructor
When a constructor without any argument or parameter called No-arg constructor. It’s very much similar to the default constructor. Let’s have a look at No-arg constructor in Java.
class Demo { public Demo() { System.out.println("This is a no argument constructor"); } public static void main(String args[]) { Demo obj = new Demo(); } }
When Demo obj = new Demo(); statement execute, It called the Demo constructor and print the message in the console.
Parameterised constructor
A Constructor with argument/parameter is called as a parametrised constructor. If we want to initialise the members or fields of a class with our own, that time we have to use a parameterised constructor.
public class Employee { int empId; String empName; //parameterized constructor with two parameters Employee(int id, String name){ this.empId = id; this.empName = name; } void info() { System.out.println("Id: "+empId+" Name: "+empName); } public static void main(String args[]) { Employee obj1 = new Employee(10245,"Chaitanya"); Employee obj2 = new Employee(92232,"Negan"); obj1.info(); obj2.info(); } }
What if you implement only parameterised constructor in a class?
Let us take an example to understand what’s the problems we are going to face when we have declared only parameterised constructors
class Example3 { private int var; public Example3(int num) { var=num; } public int getValue() { return var; } public static void main(String args[]) { Example3 myobj = new Example3(); System.out.println("value of var is: "+myobj.getValue()); } }
Output: If we run the above program, then we will get a compilation error. When the Java compiler execute this statement
Example3 myobj = new Example3();
The above statement will invoke the default constructor, but in our program, there is no default constructor. Because when we don’t implement any constructor in our program that time java compiler implements the default constructor in our class but when we implement any constructor that time you don’t receive the default constructor which was provided by the compiler.
If we remove the parametrised constructor, then the program runs appropriately because that time Java compiler inserts the default constructor into the code.
Constructor Chaining
When a constructor of class calls another constructor of the same class that’s called constructor Chaining. For better understanding, let us go with a simple program.
Use of Super() In Constructor
Whenever a child class constructor wants to implicitly call the constructor of the parent class at that time we can use the super(), in all the sub-classes the first statement of a child class constructor is a super(); statement.
class MyParentClass { MyParentClass() { System.out.println("MyParentClass Constructor"); } } class MyChildClass extends MyParentClass { MyChildClass() { System.out.println("MyChildClass Constructor"); } public static void main(String args[]) { new MyChildClass(); } }
Constructor Overloading
Constructor overloading in Java is a concept of having more then one constructor with different parameters list and each constructor is performing a different task as per the requirement.
New Thing: How Default Constructor & Static Block Called In Java With Example?
Default Constructor Java Program: How Default Constructor & Static Block Called In Java With Example?
package com.java.Softwaretestingblog; public class DefaultconstructorCallingVSStatic { DefaultconstructorCallingVSStatic () { System.out.println ("Default Constructor Called"); } static { System.out.println ("Static Block Executed"); } public static void main (String[]args) { DefaultconstructorCallingVSStatic obj = new DefaultconstructorCallingVSStatic (); } }
Check Also: Declare and Implement Interface in java
Output:
Static Block Executed Default Constructor Called
How The Default constructor Called in Java With Example
package com.java.Softwaretestingblog; public class Default_constructor { Default_constructor() { System.out.println("Default Constructor Called"); } public static void main(String[] args) { // TODO Auto-generated method stub Default_constructor obj=new Default_constructor(); } }
Check Also: Static Block Works In Java With Example
Output:
Default Constructor Called
Copy Constructor
In Java, the copy constructor is mainly used to copy the values of one object to another object.
A class inherits constructor Java Program: How To Check Class inherits constructor of other class or Not?
package com.java.Softwaretestingblog; class a { a() { System.out.println("Super Class Constructor Called"); } } public class Class_inherits_Class_constructor extends a { Class_inherits_Class_constructor() { } public static void main(String[] args) { // TODO Auto-generated method stub Class_inherits_Class_constructor obj=new Class_inherits_Class_constructor(); } }
Check Also: Default constructor Called in Java
Output:
Super Class Constructor Called
Ref: article
This is the Best Site for the Software Test Engineers