-3

If I have a class that looks like this:

class Web {
    WebDriver driver; 
    
    public Web(WebDriver driver) {
        this.driver = driver;
    }
}

will this.driver used throughout the Web class affect the original driver that was passed in? I need them to both reference the same object.

Som
  • 1,522
  • 1
  • 15
  • 48
mastercool
  • 463
  • 12
  • 35
  • yes. this is because classes are from reference type. If you want to avoid it use deep clone of the object – avivgood2 Sep 01 '20 at 15:43
  • "I need them to both reference the same object" -- yes, when you say `this.driver = driver` you do exactly that. – printf Sep 01 '20 at 16:05

2 Answers2

0

Yes, in Java any object that is not a primitive is passed as a reference. So if you want to have control on the object inside this class or from wherever you called, it is possible. The drawback is that you cannot assume an object will never be changed in you class, unless you create a copy of it (for example with a clone() )

PBeaumont
  • 11
  • 5
0

Yes it will. When a method performs an operation using the reference in this.driver, it will be performing an operation on the same WebDriver that you passed to the constructor. If that method modifies the state of the object ... it is the object that you passed in that is being modified.

  • Java call semantics are "call by value" aka "pass by value"
  • When you pass an object, the value you are passing is the reference to the object.
  • Java doesn't make copies of objects implicitly.

In your example code in the question, you are not actually modifying the object that you passed to the constructor. (But you certainly could ...)

If you don't what the constructor (or some other method of the class) to be able to modify the object passed to it, you could:

  • pass it an immutable object, or
  • pass it a copy (or clone) of the original object.
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Yes, I need this.driver to be the same object as driver. when I change one, I want the other one to change., How should i do this? – mastercool Sep 01 '20 at 16:00
  • Yes, if you say `this.driver = driver` then your variable `this.driver` will actually be a reference to the same object as `driver`. – printf Sep 01 '20 at 16:02