< Prev
Next >



Constructors in Java





Constructor is used to create an object of a class using the new keyword, where an object is also known as 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, each version with a different 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 a compiler knows which constructor to call?
Based on the type 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 arguements is invoked and int values are passed to it.



Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter




< Prev
Next >
< Overriding
Coupling and cohesion >
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
Python

Ad2