1

I would like to know if the value of c3 in ClassOne and ClassTwo are considered the same instance of that object. I plan on calling ClassThree´s check() method from both classes in seperate threads and want to know if they will interfere with each other.

 public class ClassOne{
    private ClassThree c3 = new ClassThree();
    public ClassOne(){}

    public void passThreeToTwo{
       ClassTwo.setC3(c3);
    }
 }
//------------------------------------------------------*

 public class ClassTwo{
    private static ClassThree c3 = null;
    public ClassTwo(){}

    public static void setC3(ClassThree c3){
       this.c3 = c3;
    }
 }
//------------------------------------------------------*

 public class ClassThree{
    public ClassThree(){}
    public synchronized check(){}
 }

 public static void main(String[] args){
    ClassOne c1 = new ClassOne();
    C1.passThreeToTwo();
 }

Hope it's an understandable example and question?

Hozei
  • 33
  • 3
  • Apparently you are just learning Java. In the future, if you want to know if a particular instance of an object is the same object reference (point to the same location), all you have to do is check for equality using the `==` operator. Therefore, if `obj1 == obj2` returns `true`, they are the same object reference. If this check fails (returns false), the are not pointing to the same location, but they could still hold the same value. To determine that, you have to "look inside" the object and examine its data members for value equality. – hfontanez Nov 03 '14 at 18:45
  • @hfontanez Oh sorry today I came to know this. Thanks – Devavrata Nov 03 '14 at 18:51
  • @Devavrata, i would like your coment but i cant. – Hozei Nov 03 '14 at 18:54
  • 1
    @Devavrata Remember that if the object contains data members that are objects (or arrays) themselves, you have to continue "looking inside" to determine their value. Obviously, if `obj1 == obj2` returns `true` there is no need to examine internal values for equality. – hfontanez Nov 03 '14 at 18:54

2 Answers2

2

Yes. When you do this:

public static void setC3(ClassThree c3)

you're not passing a copy of ClassThree - you're passing a reference to the original c3. You pass objects by reference (as opposed to primitives, which are copied).

You can check this by performing a reference equality check e.g.

if (c3 == myOriginalC3) {
   // it's the same
}

since this compares the object references alone.

Brian Agnew
  • 254,044
  • 36
  • 316
  • 423
2

Yes, when you "pass an object" in Java, you are really just passing a reference to the same object. Java uses pass by reference. You're talking about pass by value, which Java does NOT support for objects.

Andres Olarte
  • 4,260
  • 3
  • 21
  • 44