public class Pet implements Cloneable
1:
2: /**
3: Class for basic pet data: name, age, and weight.
4: This version implements the Cloneable interface.
5: */
6: public class Pet implements Cloneable
7: {
8: private String name;
9: private int age; //in years
10: private double weight;//in pounds
11:
12: public Object clone( )
13: {
14: try
15: {
16: return super.clone( );//Invocation of Object's clone
17: }
18: catch(CloneNotSupportedException e)
19: {//This should not happen
20: return null; //To keep the compiler happy.
21: }
22: }
23:
24: public Pet(String initialName, int initialAge,
25: double initialWeight)
26: {
27: name = initialName;
28: if ((initialAge < 0) || (initialWeight < 0))
29: {
30: System.out.println("Error: Negative age or weight.");
31: System.exit(0);
32: }
33: else
34: {
35: age = initialAge;
36: weight = initialWeight;
37: }
38: }
39:
40: public void setPet(String newName, int newAge, double newWeight)
41: {
42: name = newName;
43: if ((newAge < 0) || (newWeight < 0))
44: {
45: System.out.println("Error: Negative age or weight.");
46: System.exit(0);
47: }
48: else
49: {
50: age = newAge;
51: weight = newWeight;
52: }
53: }
54:
55: public Pet(String initialName)
56: {
57: name = initialName;
58: age = 0;
59: weight = 0;
60: }
61:
62: public void setName(String newName)
63: {
64: name = newName; //age and weight are unchanged.
65: }
66:
67: public Pet(int initialAge)
68: {
69: name = "No name yet.";
70: weight = 0;
71: if (initialAge < 0)
72: {
73: System.out.println("Error: Negative age.");
74: System.exit(0);
75: }
76: else
77: age = initialAge;
78: }
79:
80: public void setAge(int newAge)
81: {
82: if (newAge < 0)
83: {
84: System.out.println("Error: Negative age.");
85: System.exit(0);
86: }
87: else
88: age = newAge;
89: //name and weight are unchanged.
90: }
91:
92: public Pet(double initialWeight)
93: {
94: name = "No name yet";
95: age = 0;
96: if (initialWeight < 0)
97: {
98: System.out.println("Error: Negative weight.");
99: System.exit(0);
100: }
101: else
102: weight = initialWeight;
103: }
104:
105: public void setWeight(double newWeight)
106: {
107: if (newWeight < 0)
108: {
109: System.out.println("Error: Negative weight.");
110: System.exit(0);
111: }
112: else
113: weight = newWeight; //name and age are unchanged.
114: }
115:
116: public Pet( )
117: {
118: name = "No name yet.";
119: age = 0;
120: weight = 0;
121: }
122:
123: public String getName( )
124: {
125: return name;
126: }
127:
128: public int getAge( )
129: {
130: return age;
131: }
132:
133: public double getWeight( )
134: {
135: return weight;
136: }
137:
138: public void writeOutput( )
139: {
140: System.out.println("Name: " + name);
141: System.out.println("Age: " + age + " years");
142: System.out.println("Weight: " + weight + " pounds");
143: }
144: }