-1

Suppose I have three constructors in a class:

public class MyClass {
    Parent thingA;
    Child thingB;
    boolean someBoolean;
    double someDouble;
    double anotherDouble;

    public MyClass(Parent thingA, boolean someBoolean) {
       this(thingA, someBoolean, 0.25);
    }

    public MyClass(Child thingB, boolean someBoolean, double anotherDouble) {
       // Casting to prevent recursive constructor call
       this((Parent) thingB, someBoolean, 0.5);
       this.thingB = thingB;
       this.anotherDouble = anotherDouble;
    }

    public MyClass(Parent thingA, boolean someBoolean, double someDouble) {
       this.thingA = thingA;
       this.someBoolean = someBoolean;
       this.someDouble = someDouble;
    }  
}

Where Child extends Parent. My question is, when I call another constructor from a constructor in Java via this(...), am I passing by reference or passing by value? How does casting affect it? If I were to use the second constructor and modify a property of thingB, would that reflect in thingA?

Edit: I have both thingA and thingB fields because sometimes my class will be used without an instance of Child, but when Child is used, I need to take advantage of specific behaviors of Child.

Richik SC
  • 864
  • 1
  • 8
  • 18
  • 2
    Always by reference. – Antoniossss Sep 29 '18 at 18:13
  • by-reference-by-value is the most upvoted java question on SO – Maxim Sep 29 '18 at 18:17
  • @Antoniossss [This question](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) Says pass by value. However, I want to know whether it applies in constructor chaining and in casting scenarios. – Richik SC Sep 29 '18 at 18:18
  • 1
    Its pass by reference - guy that answered is most probably c++ dev where something similar to pointer was called "reference". All in all Java is always pass by reference no matter what that guy says. – Antoniossss Sep 29 '18 at 18:21
  • 1
    There is no difference between calling methods or other constructors. And Java does call by value, but guess what the value of a reference is... – GhostCat Sep 29 '18 at 18:23

1 Answers1

-2

In Java, all objects (non-primitive types) are passed by reference. Casting has no effect on this behavior. If this isn't what you want, you can create a copy of your object (you'll need to implement this behavior yourself, usually either as a method or constructor) and then pass that copy instead.

apetranzilla
  • 5,331
  • 27
  • 34
  • Thank you - I don't want to create a copy of my object, I want changes in thingA to reflect in thingB and vice versa. – Richik SC Sep 29 '18 at 18:18