Constructor In Java:

  • Constructor is special type of method which is executed at the time of instance or object creation.
  • In java, every class should have a constructor, if a class does not have any constructor then compiler writes a constructor at the time of compilation such constructors are called default constructors.
  • Default constructor will not have any argument.
  • A programmer can also develop the constructor inside the class, in such cases programmer has to follow below rules-
  •  Constructor should not have any return type not return value declared.
  •  Constructor name should be same as class name.
  •  When object is created by 'new' operator, the constructor has to be called by the 'new' operator.
  •  While creating an instance of a class if one have to perform any task at the time of instance creation, declare that particular task inside the constructor body.
  • Constructor are used to initialize instance member (non-static members) of the class at the time of object creation.
  • In a single java class, we can develop more than one constructor, the argument list should differ b/n the constructors such constructors are called overloaded constructors. The argument list should differ in either of the below 3 ways-
  • Type of arguments should be different.
  • Number of argument should be different.
  • Position of arg should be different.
  • When one have to create an instance of a class with different initialization or different operation at the time of instance creation, then we go for overloaded constructors.
  • When java is invoking the constructors, constructors are invoked based on the argument list.
Note-
  • There can not be any java program without constructor.
  • instance and object both are same.
Note:
  • As soon as object is created, it will call the constructor.
  • If one do not have object then constructor will not be called.
  • If one don't write any constructor then compiler will write the default constructor while compilation.
  • If a programmer write even a single constructor, compiler will not write any constructor.
  • Default constructor has the same access modifier as the class.
ex-

1) public class Sample {
    Sample (){
        System.out.println("Object creation by constructor");
    }
    public static void main(String[] args) {
        System.out.println("program starts");
        Sample object = new Sample ();
        System.out.println("Program ends.");
    }
}


Output-
program starts
Object creation by constructor
Program ends.

Constructor Overloading:

Before going through the sample programs of constructor overloading, we should know why constructor overloading is needed and what the purpose behind constructor overloading is.

Constructor overloading is the process where constructor contains different types of arguments or parameters so that constructors can perform different type of tasks.

Sample Program:

package com.sample;
public class SampleDemo {
 int sum,sum1;
 SampleDemo (int a, int b){//here the constructor contains two integer value 
  sum = a + b ;// sum of int a and int b
        System.out.println("sum is :"+ ""+ sum);
    }
 SampleDemo (String str){//here the constructor contains string value
        System.out.println("New string is :"+ ""+ str);
    }
    SampleDemo (double t){//here the constructor contains double value
        System.out.println("double value is :"+ ""+ t);
    }
    public static void main(String[] args) {
        System.out.println("program starts");
        SampleDemo sam = new SampleDemo (10 , 20);//here the constructor contains two integer value and it will call 1st constructor
        SampleDemo sam1 = new SampleDemo ("hello");//here the constructor contains string value and it will call 2nd constructor
        SampleDemo sam2 = new SampleDemo (20.3);//here the constructor contains double value and it will call 3rd constructor
        System.out.println("Program ends.");
    }
}

Output :
program starts
sum is :30
New string is :hello
double value is :20.3
Program ends.

Use of Private Constructor:
  • Normally private constructor is used for singleton design pattern.
  • Singleton design pattern limits the creation of an object to only one.
Before going through singleton design pattern, we should get to know why private constructor is used or what the purpose of private constructor in a program is.

Use of Private constructor:

To prevent instantiation of an object from outside of the project, the following cases shall be observed:
  • Singleton
  • Factory method
  • Static methods only – class
  • Constants – class  
If you make the constructor private, and then create a visible constructor method that returns instances of the class, you can do things like limiting the number of creations or recycle instances or other construction-related tasks.

Sample Program:

package com.sample;
public class SingletonClass {
    //Static Class Reference
    private static SingletonClass obj=null;
    private SingletonClass(){
       /*Private Constructor will prevent 
        * the instantiation of this class directly*/
    }
    public static SingletonClass objectCreationMethod(){
  /*This logic will ensure that no more than
   * one object can be created at a time */
  if(obj==null){
      obj= new SingletonClass();
  }
         return obj;
    }
    public void displayNow(){
  System.out.println("My Singleton Class");
    }
    public static void main(String args[]){
  //Object cannot be created directly due to private constructor 
         //This way it is forced to create object via our method where
         //we have logic for only one object creation
     SingletonClass myobject= SingletonClass.objectCreationMethod();
  myobject.displayNow();
    }
 }

 Answer:
  • Yes, when we define a class to be an Abstract Class it cannot be instantiated but that does not mean an Abstract class cannot have a constructor. 
  • Each abstract class must have a concrete subclass which will implement the abstract methods of that abstract class. 
  • If we are not creating any constructor for abstract class, the java by default will create a constructor like other java class.
If we are in one of these below situation, we need to create constructor in an abstract class:
  • You have defined final fields in the abstract class but you did not initialize them in the declaration itself; in this case, you MUST have a constructor to initialize those fields
Sample Program:

package com.sample;

abstract class Motor { 
    int somenewProduct;
    public Motor( int somenewProduct ) {
        this.somenewProduct = somenewProduct;
    }
    public int MotorIncrese(int val) {
       return somenewProduct * val;
    }
}
class Honda extends Motor {
    public Honda() {
        super(2);
    }
}
class Cycle extends Motor {
    public Cycle(int cycleName) {
        super(cycleName);
    }
}



1 comment:

  1. I always love to use constructor in Java, but sometimes I dont use it in the right way. Thats why I started to look for some fine explanation and found out this amazing service that absolutely the best about constructor method java https://explainjava.com/java-constructor/ its very understandable even for beginner in this language.

    ReplyDelete

Copyright © 2017 QALEARNINGGUIDE.COM || ALL RIGHTS RESERVED