Java, .NET, PHP, PYTHON, ANGULAR, .NET, ML, Data Scince, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

Constructor in Java:-



It is used to initialize the value of dynamic data member of the class. Constructor name and class name both will be same.

The constructor has no return type in declaration it will automatically return class type data.

The Constructor will be called automatically when we create an Object.

When we compile class then Constructor block will be created by default.

Class Hello
{
    Hello()
   {


  }


}


Type of Constructor:-


1 Default:-

This Constructor will be created by default if we want to initialize any data member of class then we can create default constructor block.



2 Parametrized:-

This Constructor contains set of parameters to pass value from the object and contain by parameters.


class A
{
    A(int a,int b)
   {

   }


}

A obj = new A(10,20);




3 Copy or Reference Type:-

It is similar to parametrized constructor but we can pass the value as a reference to param constructor to copy the value of one object to another.


class A
{
     A()
    {

     }
     A(A obj)
    {


    }



}

A obj = new A();
A obj1 = new A(obj);




class ConsDemo
{
    int a,b;
    ConsDemo()
    {
        a=100;
        b=200;
     
    }
    ConsDemo(int a,int b)
    {
        this.a=a;
        this.b=b;
    }
    ConsDemo(ConsDemo o)
    {
        this.a=o.a;
        this.b=o.b;
    }
    void displayAdd()
    {
       System.out.println(a+b);
    }

public static void main(String args[])
 {
     ConsDemo obj=new ConsDemo();
     obj.displayAdd();
     ConsDemo obj1 = new ConsDemo(10,20);
     obj1.displayAdd();
     ConsDemo obj2 = new ConsDemo(obj);
     obj2.displayAdd();
   

  }
}











Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post