Beruflich Dokumente
Kultur Dokumente
public MyDefaultConstructor()
Output
I am inside default constructor...
this.name = str;
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.
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");
}
Output
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...");
}
}
/**
* Create a static method to get instance.
*/
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
There are many ways to copy the values of one object into another in java. They are:
o By constructor
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. }
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:
Constructor must not have return type. Method must have return type.
Constructor name must be same as the Method name may or may not be
class name. same as class name.