-4

Dea All,

I have the following:

class test {
    int x = 6;
    int y = 7;

    private int getX() {
        return x;
    }

    private int getY() {
        return y;
    }

    public test copy() {
        test myTest = new test();
        myTest.x = getX();
        myTest.y = getY();
        return myTest;
    }
}

However, when I then execute:

test a = new test();
test b = a.copy();
b.x = 17;
System.out.println(a.x);

The result is still 17. However, shouldn't deep copying prevent this?

Anybody who can help me?

MrD
  • 4,986
  • 11
  • 48
  • 90

2 Answers2

3

First of all, you are ignoring the return value of b.copy() in:

test b = new test();
b.copy();

Secondly, I've tested your code and it prints 6 and not 17 as you say in the question.

edit I notice that you've fixed the first issue in an edit. However, the code still doesn't behave the way you say it does.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

The result should be 6 not 17.

sowrov
  • 1,018
  • 10
  • 16