Illustration of copy constructor Todo: + finish the copy constructor so the new object has the same
Question:
Illustration of copy constructor
Todo:
+ finish the copy constructor so the new object has the same
shot records as the one it copies from.
+ add code to the main method to copy more Pet objects,
give each of them multiple "vacinate" calls, and display the objects
after each vacinate call.
*/
class Pet {
private String type;
private String name;
private String owner;
private String[] shots; //to hold vacination records
private int count; //shots count
public Pet(String type, String name, String owner){
this.type = type;
this.name = name;
this.owner = owner;
this.shots = new String[5];
this.count = 0;
}
//copy constructor
public Pet(Pet x){
this.name = x.name;
this.type = x.type;
this.owner = x.owner;
this.shots = new String[x.shots.length];
//copy all the shot records over
}
//vacinate a pet
public void vacinate(String desc){
//make sure no more shots than we can hold
if(this.count < this.shots.length)
this.shots[this.count++] = desc;
}
//change owner name
public void setOwner(String ownerName){
this.owner = ownerName;
}
//representing a pet object as a string
public String toString(){
String tmp = "";
for(int i = 0; i < this.count; i++)
tmp += this.shots[i] + " ";
return "Type: " + this.type + " " +
"Name: " + this.name + " " +
"Owner name: " + this.owner +
" Vacines: " + tmp;
}
}
/** testing the Pet class */
public class Feb3{
public static void main(String[] args){
Pet p = new Pet("Dog", "Yulu", "Ken");
p.vacinate("Flu");
System.out.println("P: " + p);
Pet p2 = new Pet(p);
p2.vacinate("Deworm");
System.out.println("P2: " + p2);
p.setOwner("John");
System.out.println("P: " + p);
System.out.println("P2: " + p2);
}
}
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill