CodesJava

Easy learning with example program codes

how to copy values from one object to another java?


Example

/**
 * This program is used to copy the values one object
 * into another object using constructor.
 * @author CodesJava
 */
public class ConstructorExample6 {
       int num;
       String str;               
 
       ConstructorExample6(int n, String s){
            System.out.println("Constructor called.");
            num = n;
            str = s;
       }
 
        //This constructor will copy the value
        //of one object into another.
        ConstructorExample6(ConstructorExample6 obj){
            System.out.println("Constructor called for copying value.");
            num = obj.num;
            str = obj.str;
        }
 
        public static void main(String args[]){
           //parameterized constructor call
           ConstructorExample6 obj1 = new ConstructorExample6(10, "CodesJava");
 
           //print values of object properties.  
           System.out.println("obj1 num = " + obj1.num);
           System.out.println("obj1 str = " + obj1.str);
           //Constructor call to copy the value
           //one object into other.
           ConstructorExample6 obj2 = new ConstructorExample6(obj1);
           //print values of object properties. 
           System.out.println("obj2 num = " + obj2.num);
           System.out.println("obj2 str = " + obj2.str);
       }
}

Output

Constructor called for copying value.
obj2 num = 10
obj2 str = CodesJava

Java interview questions on main method

Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki