Menu
Question Index
...

What will be the output of the following program?

class CloneTest extends Object {
    int val = 50;
    protected CloneTest clone() {
        CloneTest result = new CloneTest();
        result.setVal(val);
        return result;
    }
    public void setVal(int val) {this.val = val;}
}
class MyClass {
    String name;
    Integer id;
    CloneTest test;
    public CloneTest getTest() { return test; }
    public void setTest(CloneTest test) {this.test = test;}
    protected MyClass clone() {
        MyClass myClass = new MyClass(name, id);
        myClass.setTest(test.clone());
        return myClass;
    }
    protected MyClass copy() {
        MyClass myClass = new MyClass(name, id);
        myClass.setTest(test);
        return myClass;
    }
    public void setName(String name) {this.name = name;}
    public void setId(Integer id) { this.id = id; }
    public boolean equals(Object arg0) {
        return ((MyClass) arg0).name.equals(name) && ((MyClass) arg0).id.equals(id);
    }
    public MyClass(String name, Integer id) {
        this.name = name;
        this.id = id;
        setTest(new CloneTest());
    }
}
public class CopyTest {
    public static void main(String... str) {
        MyClass myClass1 = new MyClass("Mahi", 575);
        myClass1.setId(555);
        MyClass clone = myClass1.clone();
        MyClass copy = clone.copy();
        myClass1.setName("Nani");
        MyClass classCopy = myClass1.copy();
        myClass1.setId(255);
        CloneTest cloneTest = new CloneTest();
        cloneTest.setVal(122);
        myClass1.setTest(cloneTest);
        System.out.print(copy.equals(clone) + " " + (copy == clone) + " " + (copy == classCopy) + " " + copy.equals(classCopy) + " ");
        System.out.print(clone.getTest().val + " ");
        System.out.println(classCopy.getTest().val);
    }
}


true false false false 50 50
true false false true 50 50
true false false false 50 122
true false false true 50 122
Some other output
Compilation Error or Runtime Error

Doubts

Problems

Topic: Object As A Super Class In Java

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App