Constructor in Java - Javastudypoint

Monday, December 31, 2018

Constructor in Java

  • In Java, a constructor is a member function of a class. 
  • The name of the constructor is the same as the name of the class like see below.
class Hello
{
Hello()   // Constructor
{
  // methods.
}
}
  • It has no return type, so we can't use the return keyword.
  • It must be an instance member function, that is, it can never be static.
  • All the classes have a default constructor in Java.
  • When there is no constructor defined in the class by the programmer, the compiler implicitly provides a default constructor for the class.
  • A constructor can be parameterized.
  • A constructor can be overloaded.


When is a constructor called?

Whenever we are creating an instance of the class using the new keyword by default a constructor is called implicitly known as default constructor. It initializes the newly created object.
For example, in this case, we make an object of class MyClass using the new keyword.

class MyClass
{
MyClass()
{
   // methods.
}
public static void main(String args [])
{
MyClass obj = new MyClass();  // instance created using new keyword.
}
}

Rules for creating a constructor:

  • Constructor name and class name must be the same.
  • A constructor cannot have any return type.
  • It can never be static, abstract, and final.

Types of constructor in Java:

There are two types of constructor in Java.
1. Default (no-argument) constructor.
2. Parameterized constructor.

1. Default Constructor in Java:

When there is no constructor defined in the class by the programmer, the java compiler implicitly provides a default constructor for the class. This constructor is known as the default constructor in java. It doesn't accept any parameter. If we create any constructor in our class then java compiler doesn't create any constructor in our class.

Example of Default Constructor:

class Test{
 int a;
 int b;
 Test(){
  System.out.println("We are inside default constructor");
  a = 10;
  b = 20;
 }
 public void display(){
  System.out.println("Value of a is: " +a);
  System.out.println("Value of b is: " +b);
 }
}
class ConstructorDemo{
 public static void main(String args[]){
  Test obj = new Test();
  obj.display();
 }
}

Output:


2. Parameterized Constructor in Java:

A constructor that accepts one or more parameter is known as a parameterized constructor. Whenever we have to create an object of the class that has parameterized constructor, we need to pass the arguments so that this constructor gets invoked after creation object.

Example of Parameterized Constructor:

In this example, we are going to show you how to calculate an area of a Rectangle using a parameterized constructor. Here we have created the constructor of Rectangle class that have two parameters (length, and width).

class Rectangle{
 int length;
 int width;
 int result;
 Rectangle(int x, int y){
  length = x;
  width = y;
 }
 public void rectArea(){
  result = length * width;
  System.out.println("Area of rectangle is: " +result);
 }
}
class ConstructorDemo{
 public static void main(String args[]){
  Rectangle obj = new Rectangle(10,20);
  obj.rectArea();
 }
}

Output:

Constructor Overloading in Java:
Constructor overloading is just like method overloading. When more than one constructor is defined in a class with different parameter list, then it is called constructor overloading in java or use of multiple constructors in a class. In constructor overloading, every constructor performs a different task.




Example of Constructor Overloading in Java:


class Student{
 int rollno;
 String name;
 int age;
 
 Student(int r){
  rollno = r;
 }
 Student(int r, String n){
  rollno = r;
  name = n;
 }
 Student(int r, String n, int a){
  rollno = r;
  name = n;
  age = a;
  
 }
 public void display(){
  System.out.println(rollno + " " + name + " " +age);
 }
}
class ConstructorDemo{
 public static void main(String args[]){
  Student obj1 = new Student(101);
  Student obj2 = new Student(101, "Prashant");
  Student obj3 = new Student(101, "Prashant", 21);
  obj1.display();
  obj2.display();
  obj3.display();
 }
}


Output:

Constructor Chaining in Java:

  • A constructor can call others constructors of the same class or superclass. 
  • Constructor call from a constructor must be the first step (call should appear in the first line).
  • The first line of the constructor is either super() or this() (by default super()). 
  • super() keyword calls the superclass constructor.
  • this() keyword calls the same class constructor.
  • Such series of invocation of constructors is known as Constructor Chaining in Java.
  • Constructor never contains super(), and this() both.
  • It contains either super(), or this().
  • The process of constructor chaining can be achieved through inheritance.

Example of Constructor chaining in java:


class Person{
 public Person(){
  System.out.println("This is person class constructor");
 }
}
class Student extends Person{
 public Student(){
  this("Prashant");
  System.out.println("This is student class constructor");
 }
 public Student(String name){
  System.out.println("Student name is Prashant");
 }
}
class ConstructorDemo{
 public static void main(String args[]){
  Student obj = new Student();
 }
}

Output:

Understand the flow of execution of a Constructor chaining example. It will help you to understand how constructor chaining work. Let's see in below fig.

Constructor in Java

Java Copy Constructor:

Copy Constructor is a constructor that is used to create a copy of an already existing object of the same class. It takes a single argument whose type is that of the class containing constructor.
Unlike C++, there is no copy constructor in java. But we can copy the value of one object into another in java by a constructor, assigning the value of one object into another, and by object cloning (clone() method of object class).

Example of Java Copy Constructor:

In this example, we are going to show you how we can copy the value of one object into another object using java constructor.

class Employee{
 int id;
 String name;
 
        //constructor to initialize integer and string 
 Employee(int i, String n){
  id = i;
  name = n;
 }

        //constructor to initialize another object  
 Employee(Employee s){
  id = s.id;
  name = s.name;
 }
 void display(){
  System.out.println(id + " " + name);
 }
 public static void main(String args[]){
  Employee e1 = new Employee(101, "Prashant");
  Employee e2 = new Employee(e1);
  e1.display();
  e2.display();
 }
}

Output:



You may also like the related posts:


No comments:

Post a Comment