<class name>() {}
Employee()
{
//some code
}
<class name>(arg1, arg2) {}
Employee(int i, String n)
{
id = i;
name = n;
} ​
C++
, Java also supports copy constructor. But, unlike C++
, Java doesn’t create a default copy constructor if you don’t write your own.clone()
method of Object classthis()
is used to call same class constructor where as super()
is used to call super class constructor.// Java program to illustrate Constructor Chaining
// within same class Using this() keyword
class Temp
{
// default constructor 1
// default constructor will call another constructor
// using this keyword from same class
Temp()
{
// calls constructor 2
this(5);
System.out.println("The Default constructor");
}
// parameterized constructor 2
Temp(int x)
{
// calls constructor 3
this(5, 15);
System.out.println(x);
}
// parameterized constructor 3
Temp(int x, int y)
{
System.out.println(x * y);
}
public static void main(String args[])
{
// invokes default constructor first
new Temp();
}
}
class FTL
{
int FTL()
{
return 0; // Warning for the return type
}
}​
PrivateConstructor.java
:class SingletonDemo {
private SingletonDemo() {
System. out.println("In a private constructor");
}
public static SingletonDemo getObject() {
// we can call this constructor
if (ref == null)
ref = new SingletonDemo();
return ref;
}
private static SingletonDemo ref;
}
public class PrivateConstructor {
public static void main(String args[]) {
SingletonDemo sObj = SingletonDemo.getObject();
}
}​
In a private constructor
class FTL
{
public FTL()
{
//No-arg constructor
}
}