





































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






































// Objects may be passed to methods.
// Constructor public ObjectParameter(int attribute1, String attribute2, double attribute3) { this.attribute1 = attribute1; this.attribute2 = attribute2; this.attribute3 = attribute3; } //Passing object2 as parameter public void myMethod(ObjectParameter obj) { obj.setmethod(5); System.out.println("Attribute 1: " + obj.attribute1); System.out.println("Attribute 2: " + obj.attribute2); System.out.println("Attribute 3: " + obj.attribute3); } public void myMethod() { System.out.println("Attribute 1: " + attribute1); System.out.println("Attribute 2: " + attribute2); System.out.println("Attribute 3: " + attribute3); } } public class ObjectParameter{ public static void main(String[] args) { ObjectParameter myObject1 = new ObjectParameter(10, "Hello", 3.14); ObjectParameter myObject2 = new ObjectParameter(20, "World", 6.28); System.out.println("Object2 before passing through method: "); myObject2.myMethod(); System.out.println("Object2 after passing through method: "); myObject1.myMethod(myObject2); // myObject2.myMethod(); //to check whether call by value or call by reference } private int attribute1; private String attribute2; private double attribute3; public void setmethod(int x) { attribute1= x; }
Object2 before passing through method: Attribute 1: 20 Attribute 2: World Attribute 3: 6. Object2 after passing through method: Attribute 1: 5 Attribute 2: World Attribute 3: 6.
Why copy constructor is required? Sometimes, we face a problem where we required to create an exact copy of an existing object of the class. There is also a condition, if we have made any changes in the copy it should not reflect in the original one and vice-versa. For such cases, Java provides the concept of a copy constructor. Copy Constructor In Java, a copy constructor is a special type of constructor that creates an object using another object of the same Java class. It returns a duplicate copy of an existing object of the class. Use of Copy Constructor We can use the copy constructor if we want to:
Recursion