Sie sind auf Seite 1von 8

Java Default Constructor Examples

 Default constructor refers to a constructor that is automatically created by compiler in the


absence of explicit constructors.
 You can also call a constructor without parameters as default constructor because all of its
class instance variables are set to default values.

Java Default Constructor Sample Code

public class MyDefaultConstructor

public MyDefaultConstructor()

System.out.println("I am inside default constructor...");

public static void main(String a[])

MyDefaultConstructor mdc = new MyDefaultConstructor();

Output
I am inside default constructor...

Java Parameterized Constructor Examples


 Parameterized constructors are required to pass parameters on creation of objects.
 If we define only parameterized constructors, then we cannot create an object with
default constructor. This is because compiler will not create default constructor. You need
to create default constructor explicitly.
Java Parameterized Constructor Sample Code

public class MyParameterizedConstructor {

private String name;

public MyParameterizedConstructor(String str)

this.name = str;

System.out.println("I am inside parameterized constructor.");

System.out.println("The parameter value is: "+str);

public static void main(String a[]){

MyParameterizedConstructor mpc = new MyParameterizedConstructor("Madhu Raj");

Output
I am inside parameterized constructor.
The parameter value is: Madhu Raj
Java Constructor Overloading Examples
Like method overloading we can overload constructors also. Along with default constructor, we can have constructors
with parameters. The no of parameters can be same, and it can have different datatypes. Below example gives
sample code for constructors overloading.

Java Constructor Overloading Sample Code

public class MyOverloading {

public MyOverloading(){
System.out.println("Inside default constructor");
}
public MyOverloading(int i){
System.out.println("Inside single parameter constructor with int value");
}
public MyOverloading(String str){
System.out.println("Inside single parameter constructor with String object");
}
public MyOverloading(int i, int j){
System.out.println("Inside double parameter constructor");
}

public static void main(String a[]){


MyOverloading mco = new MyOverloading();
MyOverloading spmco = new MyOverloading(10);
MyOverloading dpmco = new MyOverloading(10,20);
MyOverloading dpmco = new MyOverloading("java2novice");
}
}

Output

Inside default constructor


Inside single parameter constructor with int value
Inside double parameter constructor
Inside single parameter constructor with String object
Java Constructor Chaining Examples
Calling another constructor in the same class from another constructor is called constructor chaining. By using this()
we can call another constructor in the same class. Incase we want to call another constructor, this() should be the
first line in the constructor. Below example shows code for constructor chaining.

Java Constructor Chaining Sample Code

public class MyChaining {

public MyChaining()
{
System.out.println("In default constructor...");
}
public MyChaining(int i){
this();
System.out.println("In single parameter constructor...");
}
public MyChaining(int i,int j){
this(j);
System.out.println("In double parameter constructor...");
}

public static void main(String a[]){


MyChaining ch = new MyChaining(10,20);
}
}
Example Output
In default constructor...
In single parameter constructor...
In double parameter constructor...
Java Singleton Class Example Using Private Constructor
 We can make constructor as private. So that We cannot create an object outside of the class.
 This property is useful to create singleton class in java.
 Singleton pattern helps us to keep only one instance of a class at any time.
 The purpose of singleton is to control object creation by keeping private constructor.

public class MySingleTon {

private static MySingleTon myObj;


/**
* Create private constructor
*/
private MySingleTon(){

}
/**
* Create a static method to get instance.
*/
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}

public void getSomeThing(){


// do something here
System.out.println("I am here....");
}

public static void main(String a[]){


MySingleTon st = MySingleTon.getInstance();
st.getSomeThing();
}
}

Java Copy Constructor


There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in
C++.

There are many ways to copy the values of one object into another in java. They are:
o By constructor

o By assigning the values of one object into another

o By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

1. class Student6{
2. int id;
3. String name;
4. Student6(int i,String n){
5. id = i;
6. name = n;
7. }
8.
9. Student6(Student6 s){
10. id = s.id;
11. name =s.name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student6 s1 = new Student6(111,"Karan");
17. Student6 s2 = new Student6(s1);
18. s1.display();
19. s2.display();
20. }
21. }

Copying values without constructor


1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }

Can constructor perform other tasks instead of initialization?


Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the
constructor as you perform in the method.

Object Cloning in Java

The object cloning is a way to create exact copy of an object. For this purpose,
clone() method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create.
If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

1. protected Object clone() throws CloneNotSupportedException


Why use clone () method?
The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it
by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

Advantage of Object cloning


Less processing task.

1. class Student18 implements Cloneable{


2. int rollno;
3. String name;
4. Student18(int rollno,String name){
5. this.rollno=rollno;
6. this.name=name;
7. }
8. public Object clone()throws CloneNotSupportedException{
9. return super.clone();
10. }
11. public static void main(String args[]){
12. try
13. {
14. Student18 s1=new Student18(101,"amit");
15. Student18 s2=(Student18)s1.clone();
16. System.out.println(s1.rollno+" "+s1.name);
17. System.out.println(s2.rollno+" "+s2.name);
18. }
19. catch(CloneNotSupportedException c)
20. {
21. }
22. }
23. }

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.
Java Constructor Java Method

Constructor is used to initialize the state Method is used to expose


of an object. behaviour of an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default Method is not provided by


constructor if you don't have any compiler in any case.
constructor.

Constructor name must be same as the Method name may or may not be
class name. same as class name.

Das könnte Ihnen auch gefallen