0
public class Foo {
    private int field;

    public Foo(Foo foo) {
        this.field = foo.getField();
    }

    public int getField() {
        return field;
    }

    public void setField(int field) {
        this.field = field;
    }
}

Kindly can someone please help me understand this and how it will be initialized in the test class, what it does and if it is legal.

Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
Owaga_JR
  • 1
  • 1
  • 2
    what don't you understand? You just create a second instance of the class, in a new object, with the same values. You will need to be able to instantiate the original one, though, so you'll need a second constructor. – Stultuske Nov 25 '19 at 06:51
  • 1
    You might need to declare a no arg constructor too ,for your code to work. All you are doing is copying the attributes of one object to other ,by passing it to the constructor with args – Shubham Dixit Nov 25 '19 at 06:54
  • 1
    You don't have to pass an actual `Foo` object to the `Foo(Foo foo)` constructor. You could pass `null` instead: `new Foo(null)`. Just take care with the design of the `Foo` class so that having `field == null` won't cause a problem. – Kevin Anderson Nov 25 '19 at 07:04
  • @KevinAnderson Doing that is generally considered an antipattern as opposed to simply throwing NPE. (This assumes that the expected no-arg or int-arg constructor is also present.) – chrylis -cautiouslyoptimistic- Nov 25 '19 at 08:02
  • 1
    thanks guys, I really appreciate the help. @Shubh the link has helped a lot. – Owaga_JR Nov 25 '19 at 15:57

1 Answers1

1

This the working example of what you are doing .You need to define two constructors.One with no args ,as you have already defined a constructor with args.Also see copy constructor in java

 class Foo {
    private int field;

     public Foo(int arg) {
       this.field=arg;

    }


    public Foo(Foo foo) { // copy constructor
        this.field = foo.getField();
    }

    public int getField() {
        return field;
    }

    public void setField(int field) {
        this.field = field;
    }
}


public class Main {
  public static void main(String[] args) {
    Foo obj=new Foo(4); // Default constructor called
    Foo obj2=new Foo(obj);
    System.out.println(obj2.getField());
     System.out.println(obj.getField());
  }
}
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46