Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Clone Inheritance Example

Tags:

java

This clone example confuses me. I don't understand how the first two outputs can be: 111 and 222 instead of: 222 and 222. Doesn't this "a2 = (A) a1.clone();" line mean that a2 becomes the same as a1?

code:

public class Main {

    public static void main(String[] args) {
    A a1 = new A();
    A a2;
    B b1 = new B();
    B b2;

    a2 = (A) a1.clone();
    a2.setI(222);

    // Why the different output?
    System.out.println("a1 = " + a1 + " a1.i " + a1.getI()); // i = 111
    System.out.println("a2 = " + a2 + " a2.i " + a2.getI()); // i = 222

    b2 = (B) b1.clone();

    b2.setI(888); 
    b2.setJ(999); 

    System.out.println("b1 = " + b1 + " b1.i " + b1.getI() + " b1.j " +      b1.getJ());
    System.out.println("b2 = " + b2 + " b2.i " + b2.getI() + " b2.j " + b2.getJ()); 
}
}

public class A implements Cloneable {
    private int i = 111;
    @Override
    public Object clone() {
        try {
            A a = (A) super.clone();
            return a;
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }
    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
        }
    }

    public class B extends A {
    private int j = 222;

    @Override
    public Object clone() {  
        Object o = super.clone();               
        B b = (B) o;
        return b;
    }

    public int getJ() {
        return j;
    }

    public void setJ(int j) {
        this.j = j;
    }
}
like image 539
travolta andersson Avatar asked Jun 05 '26 11:06

travolta andersson


2 Answers

The values get copied across in a clone() operation, but you end up with 2 distinct objects, just that they have the same values.

a2 = (A) a1.clone()

creates a new object, entirely seperate to a1. But the internal state of a1 has been replicated into a2. Therefore, changing a2 has no effect on a1 (if the cloning is done properly!)

like image 153
Chris Knight Avatar answered Jun 07 '26 01:06

Chris Knight


No they don't point to same object anymore and hence value change of a2 doesn't affect the a1 object. That's the concept of clone() you get a same but distinct copy of the object.

When you do this

a1=(A)a2.clone();

you get a completely new object , independent of the object from which it is copied.

like image 23
kaysush Avatar answered Jun 07 '26 01:06

kaysush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!