In Java Please Write a complete class definition for a class called PostageStamp
ID: 3582637 • Letter: I
Question
In Java Please
Write a complete class definition for a class called PostageStamp. Use good principles of class design and encapsulation.
1) Write the class header and the instance data variables for the PostageStamp class.
A stamp is described by cost and description.
The description is text that describes the image on the stamp (e.g., a bell, a tree, a flag).
2) Write two constructors for the PostageStamp class:
a default (no-argument) constructor sets the cost and description to default values (e.g., 49 cents and "American flag" perhaps)
a second constructor sets the cost and description based on parameters
3) Write getters and setters for the PostageStamp class. Include appropriate validity checks.
4) Write a toString method that returns the cost and description. (You are not required to format the cost.)
5) Write an equals method for the PostageStamp class. Two stamps are the same if they have the same cost and description (ignoring capitalization).
6) The PostageStamp class implements the Comparable interface. Write an updated class header and the compareTo method.
Order stamps first by description and then by the cost.
Explanation / Answer
PostageStamp.java
public class PostageStamp implements Comparable {
private float cost;
private String description;
public PostageStamp() {
super();
this.cost=49;
this.description="American flag";
}
public PostageStamp(float cost, String description) {
super();
this.cost = cost;
this.description = description;
}
public float getCost() {
return cost;
}
public void setCost(float cost) {
if(cost>0)
this.cost = cost;
else
System.out.println("Cost can't be negative");
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
if(description!=null && !"".equals(description) )
this.description = description;
else
System.out.println("Description can't be null or empty");
}
@Override
public String toString() {
return "cost=" + cost + ", description=" + description;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PostageStamp other = (PostageStamp) obj;
if (Float.floatToIntBits(cost) != Float.floatToIntBits(other.cost))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equalsIgnoreCase(other.description))
return false;
return true;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
PostageStamp stamp=(PostageStamp)o;
int i=this.description.compareTo(stamp.description);
if(i==0){
if(this.cost>stamp.cost){
i=1;
}
else if(this.cost<stamp.cost){
i=-1;
}
}
return i;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.