Java Constructors

Constructor are used to assign initial value of data members fields. Their name is same as class name and there are no return type. Constructors are automatically executes when objects are created. That execution is depends upon parameters of objects. Because there is possible to defined more than one constructors in same class. Declaration of constructors is same as function declaration. see this syntax.

modifiers className(args){
//body
}

In this syntax modifiers is an access specifiers. That is control usability of constructor in outside of class. If that is set private that cannot access outside of class when inherited this class. After that name of constructors that is should be same as class name. Argument of constructors is similar to function arguments. for example.


class Example{
    
    /*Non-parameterized constructor( no argument accept)*/
    private Example(){
        //simple display message
        System.out.println("Constructor are executing");
    }

   public static void main(String[] args) {
      //make object of class Example
      Example obj=new Example();
   }
      
}

Output

Constructor are executing

In this examples When create Example class object (obj) ,then the executed of constructors. Note that when we are not define any constructor to within the class. then compiler is providing no-argument constructors.

Constructor Overloading in java

In Java programming, programmer can define multiple constructors in within of single class. compiler are differentiated those constructors using of its parameter arguments and data types. so we are cannot define two same signatures of constructors in java classes.

The name of constructors is same as class name. And definition of more than one constructor in same class, that is called overload of constructors. for example.


public class Student{
    int marks1,marks2;

    /*No-parameterized constructor( no argument accept)*/
    private Student(){
        //set default value
        marks1=0;
        marks2=0;
    }
    /*
    *Accepted two integer value
    */
    private Student(int marks1,int marks2){
        //set given marks value
        this.marks1=marks1;
        this.marks2=marks2;
    }

   public static void main(String[] args) {
        
      Student obj1=new Student(); //No-parameterized constructor
      Student obj2=new Student(90,95);//execute second constructor
   }
      
}
constructor overloading in java

In this example there is create two Student class object. obj1 are work on parameterless constructors. and obj2 is work on two argument of parameterized constructors.

Arbitrary number of Arguments

Some of situation we are know about how many number of parameters are accepted by constructors. That is depends upon when pass argument. This type of situations we are define arbitrary Number of Arguments constructors. There syntax as follows.

className(dataType ... variableName){
//logic here
}

Suppose for example we are add sum of all integers which are pass by constructors. in this case there is not define how many number of parameters are accepted by constructors. for example.


public class Example{
   
    long result;
    /*
    *  Accepting Arbitrary number of integer value
    */
    private Example(int ... marks){
        //get length of Arbitrary parameters
       int numberOfparms = marks.length;
       
       this.result=0; 
       for(int i=0;i<numberOfparms;i++){
            this.result+=marks[i];
       }
       //display sum of result
       System.out.println(result);
    }

   public static void main(String[] args) {
        
      Example obj1=new Example(1,2,3,4,5);//provide 5 values
      Example obj2=new Example(1,2);//provide 2 values
   }
      
}

Output

15
3

In this example there are two different arguments are accepted by same constructors. by default internally passing of this value are create in form of array and type of this array are depends on values. that is same as parameters data type.

Example arbitrary number of parameter

Clone of Java object

When we create a reference of class, and assign the object instance to this reference. then this are share and work same properties and methods of assign instance . But in some special cases we are need to clone a object. Which are hold the initial state of particular object.

class Fruits implements Cloneable{

  String type;
  int quantity;

  Fruits (String type,int quantity){
    this.type=type;
    this.quantity=quantity;
  }
  void updateQuantity(int newQuantity ){
    this.quantity=newQuantity;
  }
  void detail(){
    System.out.println("Fruit Type : "+ type);
    System.out.println("  Quantity : "+ quantity);
  }

  public Object clone()throws CloneNotSupportedException{
    //Control exception
    return super.clone(); 
  }
  public static void main(String args[]){

    Fruits apple = new Fruits("Apple",4);
    try{
      Fruits cloneApply =(Fruits)apple.clone(); //Clone object
     
      apple.detail();
      System.out.println("Clone Object");
      cloneApply.detail();

      System.out.println("\nAfter Modified");
      apple.updateQuantity(20); //modified apple object value
      
      apple.detail();
      System.out.println("\nClone Object");
      cloneApply.detail();
    }catch(CloneNotSupportedException e){
      System.out.println(e);
    }
  }
}

Output

Fruit Type : Apple
  Quantity : 4
Clone Object
Fruit Type : Apple
  Quantity : 4

After Modified
Fruit Type : Apple
  Quantity : 20

Clone Object
Fruit Type : Apple
  Quantity : 4

Java Object class are provide a clone method which are clone one object to another. This method are internally create new object and set same properties of clone object. And returns the instance of new object.

Clone the Java class object

This new clone object are different to previous object. When modifying the one object properties they are never effect to other object.

Modified Non clone object properties in java

Note that clone object by clone method is useful when we are know about how many fields are existing in particular object. When multiple field exist in any object then that is useful mechanism to control version of objects.



Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved