Reputation: 53
If I have two classes A and B as follows :
class A:
class A{
int i;
A(int j){
i=j;
}
}
class B:
class B{
A a;
B(A a){
this.a=a;
}
}
Then if I have a program that has the following statement:
A a = new A(5);
B b = new B(a);
my question is:
Am I going to have two different objects a
and b.a
, which will have the same value of i
, or is my b.a
object just pointing to the object a
and if I change the value of a.i
, then the value of b.a.i
will also change?
Upvotes: 0
Views: 97
Reputation: 7685
Because Java references are passed by value, the object pointed to by a and b.a is the exact same one, meaning that changing one 'value' changes both. So if you call a cup a tumbler and I call it a container if I put something water in it the water is in that same utensil that you call 'tumbler' and I call 'container.' Hope this example helps.
Upvotes: 0
Reputation: 1102
Same object and two pointers pointing to same object as java is pass by value
System.out.println(a.i+"--------"+a.hashCode());
System.out.println(b.a.i+"------"+b.a.hashCode());
these above two lines will print the same values. as object is same.
Upvotes: 0
Reputation: 34186
When you do
B b = new B(a);
the line
this.a = a;
will copy the reference of the A
instance. In other words, both a
and b.a
will refer to the same location in memory, where the A
instance is stored.
They are different ways to access to the same object. So, if you change one object through one of those variables, the same object will be affected.
Upvotes: 0
Reputation: 81588
There will be an instance of A, it holds an integer.
And there will be an instance of B. It receives a reference (pointer) to A.
So accessing b.a.i is going to change the integer in the instance of A.
Primitives are copied by value. For classes, the pointer to the object is copied by value.
Upvotes: 0
Reputation: 69035
Java is pass by value!
In this case value of the reference pointing to the Object is passed. So you have two references pointing to same instance of Object A.
Upvotes: 1
Reputation: 32498
There will be one A
object and two pointer a
and a.b
to that object. You can alter the state of that object by using those two references a
and b.a
.
Upvotes: 1