(In Java) Write a complete definition of a piggy bank class conforming to the fo
ID: 3834541 • Letter: #
Question
(In Java) Write a complete definition of a piggy bank class conforming to the following requirements.
-Define a constructor which accepts the number of quarters, dimes, and nickles, as parameters.
-Define a ***default constructor creating a piggy bank containing $0.
-Define an equals method (equals if all the instance variables are the same).
-Define mutators for quarters, dimes, and nickles.
-An accessor that returns the value of the piggy bank in cents (total amount stored in the piggy bank).[Quarters are 25 cents, dimes are 10 cents, nickles are 5 cents]
-Define a method breakTheBank which takes an amount in cents and determines if the piggy bank contains at least that much money or not. If so, you will return all the money in the piggy bank and remove the coins from the piggy bank. Otherwise, you will return zero.
Explanation / Answer
You don't need to create a default constructor, while creating an object JVM itself creates a default constructor and assign default value to it.
While writing accessor and mutator methods needs to follow some rules like writing first letter as capital etc.
* Here need clarification about equals method. what is it's functionality.
Here is the code you want.
public class PiggyBank {
//variables
private int quarters;
private int dimes;
private int nickles;
//default constructor
PiggyBank()
{
quarters=0;
dimes=0;
nickles=0;
}
//parameterized constructor
PiggyBank(int quarters,int dimes,int nickles)
{
this.quarters=quarters;
this.dimes=dimes;
this.nickles=nickles;
}
//Mutator methods
public void setQuarters(int quarters) {
this.quarters = quarters;
}
public void setDimes(int dimes) {
this.dimes = dimes;
}
public void setNickles(int nickles) {
this.nickles = nickles;
}
// Accessor methods
public int getQuarters() {
return quarters;
}
public int getDimes() {
return dimes;
}
public int getNickles() {
return nickles;
}
//breakthebank method which checks the availability of money in bank i.e; if amount is less than quarters, dimes, nickles
public int breakTheBank(int amount)
{
if((amount > getQuarters()) && (amount >getDimes()) &&(amount > getNickles()))
{
return 0;
}else
{
int totalamount=getQuarters()+getDimes()+getNickles();
setQuarters(0);
setDimes(0);
setNickles(0);
return totalamount;
}
}
public void equals()
{
//code for equals method..
}
public static void main(String[] args) {
PiggyBank pb=new PiggyBank();
PiggyBank pb1=new PiggyBank(25,10,5);
int amount=pb1.breakTheBank(10);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.