Copy Constructor in Java is the constructor that can be use to copy the value of an existing object to a new object. It means the new object will call the copy constructor for copying the value of an existing object. The copy constructor has a special parameter through which it can pass the reference of an existing object for the new object.
Syntax of copy constructor
Syntax Copy Constructor in Javapublic classname ( class obj) { Data=obj.data; }
Example of Copy Constructor
Input Value
Example of Copy Constructor in Javapublic class consv { int n; public consv (int t){ n=t; } public consv (consv m){ n=m.n; } public void show () { System.out.println("data:"+n); } public static void main (String args []){ consv a =new consv(20); a.show(); consv b=a; b.show(); } }
Let’s run the code
Output Value
Constructor Overloading in Java
We know, we can define multiple constructor within a class but each constructor parameters must be different from other and this also proves the concept of method overloading.
Example of Constructor Overloading
Example of Constructor Overloadingpublic class consv { private String message; public consv(){ message = "Basic Engineer"; } public consv(String message){ this.message = message; } public String getMessage(){ return message ; } public void setMessage(String message){ this.message = message; } public static void main(String[] args) { consv tester = new consv(); System.out.println(tester.getMessage()); consv tester1 = new consv("Hello Student how are you?"); System.out.println(tester1.getMessage()); } }
Let’s run the code
Output Value
This Keyword in Java
The ‘this’ keyword is use for referring data and method as current class data and method. Generally it is useful whenever class data and method’s local data have same name.
Syntax of this keyword
Syntax of this keywordthis.data/method;
Note: This.n=n; Where, (first n is class data and second n is method data)
Example of this keyword
Example of this keywordpublic class thiskeys { int n; public void input(int n) { this.n=n; } public void show() { System.out.println("input Value:"+n); } public static void main (String args[]){ thiskeys p=new thiskeys(); p.input (15); p.show(); } }
Let’s run the code
Output Value
If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.
To know more about JAVA Wikipedia please click here .
Stay Connected Stay Safe, Thank you
0 Comments