copy constructors in Java code example

Example: copy constructor in java

public class CopyConstructorExample {
  
	private int someInt;
  	private String someString;
	private Date someDate;
  
  	public CopyConstructorExample(CopyConstructorExample example) {
    	this.someInt = example.getSomeInt();
    	this.someString = example.getSomeString();
      	this.someDate = new Date(example.getSomeDate().getTime()); 
      	// We need to construct a new Date object, else we would have the same date object
    }
  
  // Other Constructors here
  // Getters and Setters here
}
public class UsageExample {
	public static void main(String[] args) {
    	CopyConstructorExample example = new CopyConstructorExample(5, "Test");
      	// Copy example using the Constructor
      	CopyConstructorExample copy = new CopyConstructorExample(example);
      	
    }
}

Tags:

Java Example