Java: What happens to the supposed-to-be initialized members when passing a value to their object at creation time?

StackOverflow https://stackoverflow.com/questions/23333621

문제

This question is more about having a proper Java program construction. I was wondering: What happens to the

public Clazz { 
   this.someClazz = new SomeClazz(); 
}  //initialization

Clazz x = y; 

Is the above constructor gets executed, or is it skipped, and someClazz memberget a new value right away?

도움이 되었습니까?

해결책

You need to distinguish between variables, objects and references.

The values of x and y are not objects - they're just references. The assignment operator just copies the value from the expression on the right to the variable on the left. So in your case, it copies the value of y into x... at that point, the values of both variables refer to the same object. No constructors or any other members get called - it's just copying a value. So for example:

// Assuming appropriate methods...
x.setFoo("new foo");
System.out.println(y.getFoo()); // Would print "new foo"

However, the two variables are still independent:

x.setFoo("new foo");
x = new Clazz();
x.setFoo("yet another foo");
System.out.println(y.getFoo()); // Would print "new foo"

Here, after the second line, the values of x and y refer to different objects, so calling x.setFoo() doesn't change the value of foo within the object that y refers to.

다른 팁

Here in code snippet Clazz x = y; , you are not making any new object. You are just telling that, now, x reference will refer to that object which y is pointing to.

When you have created an object y, Clazz y = new Clazz(); , then y starting referring to an object that is in heap.

y--------------------------> Obj1

and after Clazz x = y;

x-----> y---------> Obj1 

that is actually something like following

x--->Obj1<----y

Here, since no new object has not been created, therefore, no constructor will be called, and no member initialization would occur, i.e, this.someClazz = new SomeClazz(); wont be executed.

In you code you are not creating a new intance of your class, you simply assigning the reference of y to your variable x

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top