Advertisement



< Prev
Next >



Constructors in Java





A constructor is used to create an object of a class using the new keyword, where an object is also known as an instance of a class. Each object of a class will have its own state (instance variables) and access to methods of its class.

Some important features of a constructor are -






Overloading a constructor means providing multiple versions of a constructor, where each version has a different type or number of argument list.




Use of overloaded constructors



An example of overloaded constructor


class MathOP
{

MathOP(int a, int b)	//Constructor to add two integers
{
System.out.println(a+b);
}

MathOP(String a, String b)	//Constructor to add two integers
{
System.out.println(a+b);
}

MathOP(float a, float b)	//Constructor to add two integers
{
System.out.println(a+b);
}

MathOP(char a, char b)	//Constructor to add two integers
{
System.out.println(a+b);
}
}

class Cons
{
public static void main(String... ar)
{
MathOP ob1= new MathOP(1,2);
MathOP ob2= new MathOP("John","Denver");
MathOP ob3= new MathOP(2.5f, 2.5f);
MathOP ob4= new MathOP('a', 'b');
}
}


Output-


3
JohnDenver
5.0
195

In this program, we have created a class MathOP having multiple constructors, with each constructor involved in some specialized talk of adding two integers, characters, strings or float values.




How does a compiler know which constructor to call?
Based on the type and the number of arguments used to call a constructor, a specific constructor is called. For example -if a constructor is called with int arguments, a constructor accepting int arguments is invoked and int values are passed to it.



Please share this article -





< Prev
Next >
< Overriding
Coupling and cohesion >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement