Friday, 18 August 2017

Constructor in Java

constructor in Java is a block of code like to a method that's invoked when an instance of an object is created.

Every class has a constructor, if we don't clearly declare a constructor for any java class the compiler builds a default constructor for that class.

Main difference between method and constructor is constructor does not have any return type.

Constructor in Java can’t be abstract, static, final or synchronized.

Two types of constructor available in java

  • Default Constructor
  • Parameterized constructor


Default constructor :

Default constructor is when we don’t pass argusment to the constructor.

If we don’t create the lib automatic create blank contructor.

Code
class myclass
{
    myclass()
   {
                System.out.println("this is constructor");
   }
   public static void main(String args[])
   {
                myclass m = new myclass();
                System.out.println("this is main method");
   }
}
Output:
this is constructor
this is main method

Parameterized constructor

In parameterized constructor we pass argument or parameter in constructor.

Code
class myclass
{
   int a,b;
               
   //parameterized constructor
   myclass(int x,int y)
   {
                a = x;
                b = y;
   }
   public static void main(String args[])
   {
                int c;
                myclass m = new myclass(12,22);
                c = m.a + m.b;
                System.out.println("c : "+c);
   }
}
Output:
c : 34

Constructor overloading

Like Methods, Constructors could also be overloaded. Since the Constructors in a Class, all have the same name as the C Constructor overloading is not a lot different than method overloading. In case of method overloading you have multiple methods with same name but dissimilar signature, where in Constructor overloading you has numerous constructors with different signature but only difference is that Constructor doesn't have return type in Java. lass, their signatures are differentiated by their argument lists.


So in this post we learned constructor in java.and constructor overloading.

0 comments:

Post a Comment