1

when you run the following code, the gear value for bike1 changes to 3 as well as bike2. Can you explain why? My own guess is because bike1 and bike2 are object variables and don't actually contain any values, they're just references (labels). When they're assigned equal to each other they both change to 3. Am I right?

class Bicycle{
    int gear = 0;

    void changeGear(){
    gear = 3;
    }
}


public class BicycleApp {

    public static void main(String[] args) {
        //Create bike 1
        Bicycle bike1 = new Bicycle();
        System.out.println(bike1.gear);

        //Create bike 2
        Bicycle bike2 = bike1;
        System.out.println(bike1.gear);

        //Call the method
        bike2.changeGear();

        System.out.println(bike2.gear);
        System.out.println(bike1.gear);
    }

}
23eckham
  • 11
  • 1
  • 2
    Right, `bike1` and `bike2` both reference the same `Bicycle` object. – GriffeyDog May 26 '15 at 15:03
  • Exactly, it is the same reference : you have only one `new (...)`. I suggest you to read this : http://stackoverflow.com/questions/869033/how-do-i-copy-an-object-in-java – romfret May 26 '15 at 15:05
  • 1
    change `Bicycle bike2 = bike1` to `Bicycle bike2 = new Bicycle()` then the code matches the comment. You also call `System.out.println(bike1.gear);` twice , im expecting you should be calling `System.out.println(bike2.gear);` after creating bike 2 – Kenneth Clark May 26 '15 at 15:07

2 Answers2

3

Here:

Bicycle bike2 = bike1;

You are referring the bike2 object same reference as bike1 and then you change the gear. So whatever you do on bike2 or bike1, you will see same effect on both the object. So you could so something like:

Bicycle bike2 = new ...;

Currently its like:

      |bike1 at address1|
      |  gear 0         |

With assignment of bike2 to bike1

      |bike1 at address1|
      |  gear 0         |
            /\
             |
      |bike2 referring bike1|
SMA
  • 36,381
  • 8
  • 49
  • 73
0

Basically, your guess is right - in Java bike1 and bike2 are called object references. They reference an object BUT they are only references. With new Bicycle(); the object is created and bike1 references this newly created object.

As bike2 is "pointing" to the same object due to referencing bike1, BOTH references (can) change the ONE object. Whenever you want to have an information of the objects state - using bike1 or bike2 - the information is the same.

swinkler
  • 1,703
  • 10
  • 20