How to inherit interface from superclass - java

I have an interface with a superclass, a subclass, and a driver class. The interface must be implemented in the subclass, however, I am confused on how to do it. Do I implement the interface in the superclass and then extends the subclass?
The superclass is called store.
The subclass is called retail, it should receive the superclass's constructor, the number of items sold, unit price, and sale price should be array arguments. This class implements two methods that are defined at interface.
The interface should have two methods. One is the profit and the other is salary The profit method is to calculate the store profit in a week, and salary method is to calculate the store manager’s salary in a week.
/*
The interface should have two methods.
One is the “Profit” and the other is “Salary”.
The profit method is to calculate the store profit in a week, and salary method
is to calculate the store manager’s salary in a week.
*/
public interface Interface {
public void profit();
public void salary();
}
/*
The store class is a super class that receives store location,
manager name, hours worked, and hour rate.
This class should have the constructor that receives all of these.
It also should have get and set methods for each of fields.
This class also has “toString()” to
display restaurant location and manager’s name.
*/
public class Store {
private String location;
private String manager;
private int hours;
private int rate;
public Store(String l, String m, int hrs, int r) {
location = l;
manager = m;
hours = hrs;
rate = r;
}
public void setLocation(String l) {
location = l;
}
public String getLocation() {
return location;
}
public void setName(String m) {
manager = m;
}
public String getName() {
return manager;
}
public void setHours(int hrs) {
hours = hrs;
}
public int getHours() {
return hours;
}
public void setRate(int r) {
rate = r;
}
public int getRate() {
return rate;
}
public String toString() {
String result = "Store Location: " + location + "\n";
result += "Manager name:" + manager + "\n";
return result;
}
}
public class Retail extends Store {
private int items;
private double unit;
private double sale;
public Retail(String l, String m, int hrs, int r,int i, double u, double s){
super(l,m, hrs, r);
items = i;
unit = u;
sale = s;
}
public void profit() {
double[][] money = {{1.99, 2.99, 3.99, 4.99},
{5.99, 6.99, 7.99, 8.99},
{150, 48, 350,20}};
for (int i = 0; i < money.length; i++) {
for (int j = 0; j < money[i].length; j++) {
sum += money[i][j];
}
}
double profit = items * ( s - u);
}
public void salary() {
double pay = hrs * r;
//double salary = pay - ( pay * 0.05);
}
public double getSalary() {
double baseSalary = super.getHours();
}
public String toString() {
result += super.getName(); // inherited from superclass
String result = "Total Benefit: " + profit + "\n";
result += "Salary: " + salary + "\n";
return result;
}
}

General rules:
If the interface contract is applicable in the full hierarchy then implement it in the superclass and all subclasses adhere to the interface contract automatically.
You may choose to implement the interface in the superclass but make the superclass abstract if it does not have enough details to implement the interface methods. This way you can enforce the subclasses to adhere to the interface contract.
If the interface contract is not at all relevant to the full hierarchy then implement only in the applicable subclasses.
Your case:
In your example, the question is whether interface methods profit() and salary() applicable to any kind of Store? If yes (I assume it is), then go ahead and implement in the superclass. However, you may not be able to compute profit() and salary() in the Store class with the data points available. So, you may choose to declare Store class as abstract. In case you can implement these methods make Store class concrete.
On the other hand, if the interface methods profit() and salary() may not be applicable to all kind of Stores then go ahead and implement the interface only in Retail class.
Though I think the first option is the good one however, the choice is yours based on the business scenario.

Related

Understanding inheritance and different classes

I'm messing around with inheritance and confused on how to do a few different things. Here is what I have:
Looking at the Account class and write a main method in a different class Bank to brief experiment with some instances of the Account class.
Using the Account class as a base class, write two derived classes called SavingsAccount and CheckingAccount. A SavingsAccount object, in addition to the attributes of an Account object, should have an interest variable and a method which adds interest to the account. A CheckingAccount object, in addition to the instance variables of an Account object, should have an overdraft limit variable. Ensure that you have overridden methods of the Account class as necessary in both derived classes.
Now create a Bank class, an object of which contains an array of Account objects. Accounts in the array could be instances of the Account class, the SavingsAccount class, or the CheckingAccount class. Create some test accounts (some of each type).
Write an update method in the bank class. It iterates through each account, updating it in the following ways: Savings accounts get interest added (via the method you already wrote); Checking Account get a letter sent if they are in overdraft.
public class Account {
private double balance;
private int acctNum;
public Account (int num)
{
balance = 0.0;
acctNum = num;
}
public void deposit (double amt)
{
if (amt >0)
balance +=amt;
else
System.out.println("Account.deposit(...): "
+"cannot deposit negative amount.");
}
public void withdraw (double amt)
{
if (amt>0)
balance -=amt;
else
System.err.println("Account.withdraw(...): "
+"cannot withdraw negative amount.");
}
public double getBalance()
{
return balance;
}
public double getAccountNumber()
{
return acctNum;
}
public String toString()
{
return "Acc " + acctNum + ": " + "balance = "+ balance;
}
public final void print()
{
System.out.println( toString());
}
}
Now the SavingsAccount
public class SavingsAccount extends Account {
private double interest;
public SavingsAccount(int acctNum, double interest) {
super(acctNum);
this.interest=interest;
}
public double getInterest() {
double x= getBalance() + getBalance()*interest;
return x;
// public void setInterest((interest))
// this.interest=interest;
}
public void AddInterest (double interest) {
double x = super.getBalance() * interest;
super.deposit(x);
}
public String toString() {
return super.toString()+" Interest : " + interest;
}
}
CheckingAccount
public class CheckingAccount extends Account {
private double limit;
public CheckingAccount(int acctNum, double limit) {
super(acctNum);
this.limit=limit;
}
public double getLimit() {
return this.limit;
}
public void setLimit(double limit) {
this.limit=limit;
}
public void withdraw (double limit) {
if (limit <= this.limit)
super.withdraw(limit);
else {
System.out.println(" Sorry, Limit Exceeded" );
}
}
public String toString() {
return super.toString() +"Limit : "+limit;
}
}
Bank class
public class Bank {
public static void main(String[] args) {
Account[] accounts = new Account[2];
accounts[0] = new SavingsAccount(2, 0.25);
accounts[1] = new CheckingAccount(23, 50);
for(int i=0; i<accounts.length;i++) {
if (accounts[0].equals(SavingsAccount)
System.out.println(accounts[0].getInterest());
}
}
So here is my problems that I am noticing.
In the SavingsAccount I'm not sure how to get the setInterest() to work. I have tried changing it to a int, but then that changes the Account class. How do I get that to work properly?
In the bank class - the for loop I have written. Its not working, I have tried if(accounts[i].equals so so, but does not seem to function properly. What is the correct way?
As well, I'm assuming everything is coming from my SavingsAccount class.
If I understand what you are trying to do in your for-loop you need to use instanceof to check classes, not equals().
So, for example
Account[] accounts = new Account[2];
accounts[0] = new SavingsAccount(2, 0.25);
accounts[1] = new CheckingAccount(23, 50);
for(int i=0; i<accounts.length;i++) {
if (accounts[i] instanceof SavingsAccount) {
// You must cast an Account to use any of the descendant's methods
SavingsAccount account = (SavingsAccount) accounts[i];
System.out.println(account.getInterest());
} else { // it's a CheckingAccount
}
}
Other than that, StackOverflow is not a place for you to dump homework requirements, so your question is overly broad to answer in completion.

Method Inheritance and invoking

I need to inherit an instance method from the superclass but I am stuck.
public class Pay
private float hours;
private float rate;
private int hrsStr;
float gross;
double tax;
public void calc_Payroll()
{
if (hrsStr != 0)
gross = hrsStr + ((hours - hrsStr) * 1.33f) * rate;
else
gross = hours * rate;
}
public void tax(double a)
{
if (gross <= 399.99)
tax = .92;
else
if (gross <= 899.99)
tax = .88;
else
tax = .84;
}
this is the part of the super class, i need have the same method signature(???) was well as invoke tax(double a) and calc_payroll()
this is what i had for the sub class but it wasn't working.
public class Payroll extends Pay
{
float net;
void calc_payroll()
{
float finaltax = (float) tax;
net = gross * finaltax;
}
}
Your void calc_payroll() in your sub class does not either override or invoke the super class method.
If you want to override the method in your base class, the method signature must be the same. Use the #override annotation for clarity.
#override
public void calc_Payroll(float a, float b, int c, float d)
{
}
If your new method has a different signature, then you can call the super class method using....
void calc_payroll()
{
super.calc_Payroll( ... );
}
Depends what behaviour you require in your new method and if you want to invoke the behaviour in the super class method.

Im trying to get my FlexibleSavings Account and CDSavingsAccount to add interest each month and display it

My flexiblesavingsaccount is supposed to add 1.2% interest each year and it compounds monthly. CD Savings account on the other hand adds interest at 4% per year and compounds quarterly. I've managed to get the program to add interest to the balance the first month, but after that it just stays the same. and on month zero, it says the balance is 0 when it needs to be 2000 for flexiblesavingsaccount and 3000 for CDSavingsaccount. Once the program goes through 12 months it is supposed to add up the balance of the two accounts. that part works i believe, it is just that the balance I get right now it wrong
Here is my driver class:
import java.util.*;
public class SavingsAccountDriver1{
public static void main(String[] args){
FlexibleSavingsAccount1 saver1 = new FlexibleSavingsAccount1(10002,2000); //could be FlexibleSavingsAccount saver1
CDSavingsAccount1 saver2 = new CDSavingsAccount1(10003,3000);//CD SavingsAccount saver 2
saver1.annualInterestRate=.012;
saver2.annualInterestRate = .04;
int i;
System.out.println("Month\tAccount # Balance\tAccount # Balance");
System.out.println("-----\t--------- -------\t--------- -------");
System.out.print(" 0");
printFlex(saver1);
printCD(saver2);
System.out.println();
for(i=1;i<=12;i++)
{System.out.printf("%5d",i);
printIntFlex(saver1);
printIntCD(saver2);
System.out.println();
}
System.out.printf("Final balance of both accounts combined: %.2f\n",(saver1.getMonthlyInterest()+saver2.getMonthlyInterest()));
}
public static void printIntFlex(FlexibleSavingsAccount1 f){
getIntFlex(f);
printFlex(f);
}
public static void printIntCD(CDSavingsAccount1 c){
getIntCD(c);
printCD(c);
}
public static void printFlex(FlexibleSavingsAccount1 f){
System.out.printf("%12d%10.2f ",f.getAccount_Number(),f.getMonthlyInterest());
}
public static void printCD(CDSavingsAccount1 c){
System.out.printf("%12d%10.2f ",c.getAccount_Number(),c.getMonthlyInterest());
}
public static void getIntFlex(FlexibleSavingsAccount1 f){
f.addMonthlyInterest(f.getBalance());
}
public static void getIntCD(CDSavingsAccount1 c){
c.addMonthlyInterest(c.getBalance());
}
}
here is my SavingsAccount superclass:
public abstract class SavingsAccount1
{
private double balance;
private final int ACCOUNT_NUMBER;
public SavingsAccount1(){
this.balance = 0.0;
this.ACCOUNT_NUMBER =0;
}
public SavingsAccount1(int ACCOUNT_NUMBER, double balance)
{
this.balance = balance;
this.ACCOUNT_NUMBER = ACCOUNT_NUMBER;
}
public abstract void addMonthlyInterest(double balance);
public double getBalance()
{ return balance;
}
public void setBalance(double balance){
this.balance = balance;
}
public int getAccount_Number()
{
return ACCOUNT_NUMBER;
}
public String toString(){
return String.format("%s", getAccount_Number());
}//end of toString
}
Here is my FlexibleSavingsAccount subsclass:
public class FlexibleSavingsAccount1 extends SavingsAccount1{
public static double annualInterestRate;
public static double b;
public FlexibleSavingsAccount1 (int ACCOUNT_NUMBER, double balance){
super(ACCOUNT_NUMBER, balance);
}//end of
#Override public void addMonthlyInterest(double balance){
b =balance +(balance * (annualInterestRate / 12));
this.b = b;
}
public double getMonthlyInterest(){
return b;
}//end of getMonthlyInterest
public String toString(){
return String.format("%s %s", super.toString(), getMonthlyInterest());
}//end of toString
}//end of FlexibleSavings Account
Here is my CDSavingsAccount subclass:
public class CDSavingsAccount1 extends SavingsAccount1{
public static double annualInterestRate;
public static double b;
public CDSavingsAccount1 (int ACCOUNT_NUMBER, double balance){
super(ACCOUNT_NUMBER, balance);
}//end of
#Override public void addMonthlyInterest(double balance){
b =balance +(balance * (annualInterestRate / 4));
this.b = b;
}
public double getMonthlyInterest(){
return b;
}//end of getMonthlyInterest
public String toString(){
return String.format("%s %s", super.toString(), getMonthlyInterest());
}//end of toString
}//end of CDSavings Account
Sorry for all the code, I've never messed with polymorphism or inheritance before and my teacher is really bad. I assume that is where my issue is. Any help you could give would be awesome.
InSavingsAccount1 change the constructor to allow an annualInterestRate parameter to be given. Create a getter for it and it's done.
Regarding theFlexibleSavingsAccount1class (Due to the similarities with theCDSavingsAccount1class, everything I will mention applies to both classes):
When you extend a class you inherit all theattributes and methodsof the parent class so there is no need to defineannualInterestRateattribute in the child class. You see, this is precisely why we use inheritance. 1- is so we don't repite ourselves, and keep typing the same code more than once. 2- it allows us to force a common signature/behaviour. A class that extends from an abstract class must either provide an implementation to the abstract methods or must itself be abstract, adding one more layer of abstraction.
This variable b was supossely to hold the value of the monthlyInterest but you seem never to actually use it in your design.
ps: If you were to keep it, you would have to rename it to something more meaningful then justb.
So, you should eliminate both of the attributes because you never use them.
In theaddMonthlyInterestmethod you are calculating the value of the monthlyInterest and assigning to b and then you are assigning b to itself. This is obviously wrong, you need to change the actual balance of the account.
public void addMonthlyInterest(double balance) {
setBalance(balance + (balance * (annualInterestRate / 12)));
}
Pretty self-explanatory, I set a new value for the balance which is the result of the sum of the monthlyInterest with the current balance.
FlexibleSavingsAccount1 saver1 = new FlexibleSavingsAccount1(10002, 2000, .012);
CDSavingsAccount1 saver2 = new CDSavingsAccount1(10003, 3000, .04);
System.out.println("Month\tAccount # Balance\tAccount # Balance");
System.out.println("-----\t--------- -------\t--------- -------");
System.out.print(" 0");
print(saver1);
print(saver2);
System.out.println();
for (int i = 1; i <= 12; i++) {
System.out.printf("%5d", i);
printInt(saver1);
printInt(saver2);
System.out.println();
}
System.out.printf("Final balance of both accounts combined: %.2f\n",
(saver1.getBalance() + saver2.getBalance()));
}
Both FlexibleSavingsAccount1 and CDSavingsAccount1 are a type of SavingsAccount1 you and so you can eliminate several duplicated methods that you had by changing the method signature to accept a SavingsAccount1 as argument instead.
public static void printInt(SavingsAccount1 f) {
getInt(f);
print(f);
}
public static void print(SavingsAccount1 f) {
System.out.printf("%12d%10.2f ", f.getAccount_Number(),
f.getBalance());
}
public static void getInt(SavingsAccount1 f) {
f.addMonthlyInterest(f.getBalance());
}
The methodgetInt(SavingsAccoutn1 f) is a wonderful example what polymorphism is all about. You will now call this method using both child objects and both of them will addMonthlyInterest according to their own unique implementation defined in their classes. That is the definition of polymorphism: two related but different objects getting the same order but acting upon it differently.
You should rename this methods to something more explanatory.
Finally, a word about your class naming convention, namely the fact that all your classes end with a 1 attached, such as SavingsAccount1 to it's end makes me think that you not fully grasped the concept of a class. A class is a blueprint, it enables us to create many objects of the same type, as such it's name shouldn't seem to be "tied" to any particular instance/object.
NOTE: I agree with MarsAtomic in that you should stick with BigDecimal class for monetary transactions in order to not lose precision but as you state this is some kinda of assignment, I will take in assumption that the BigDecimal is beyond the scope of what your teacher taught you so I just used double.

Constructor and classes in Java

I have one class Account (abstract).
I have one class SavingsAccount (inherits Account).
I have one class CreditAccount (inherints Account).
SavingsAccount and CreditAccount are similar, except CreditAccount has a credit limit (variable limit).
I have the following problems:
I need help with how constructor in CreditAccount looks like. How can I add local variable limit to the constructor?
Is it better (easier) if I have a variable limit in base class instead, and let SavingsAccount Always set it to be zero, while CreditAccount let the user set the limit?
My teacher says since SavingsAccount and CreditAccount are almost the same, #Override are exactly the same, he recommends me to implement those methods in base class (Account). How will the code look like if I do that?
Thank you for your help
class Account:
public abstract class Account {
protected double balance = 0;
protected String accountId;
protected double interest = 0;
public Account() {}
public Account(double bal, String id, double inte) {
if (balance >= 0) {
balance = bal;
}
else {
balance = 0;
}
accountId = id;
interest = inte;
}
public abstract String getAccountId();
public abstract double getBalance();
public abstract double getInterest();
}
class SavingsAccount:
public class SavingsAccount extends Account {
public SavingsAccount() {
super();
}
public SavingsAccount(double bal, String id, double inte) {
super(bal, id, inte);
}
#Override
public String getAccountId() {
return accountId;
}
#Override
public double getInterest() {
return interest;
}
#Override
public double getBalance() {
return balance;
}
}
Class CreditAccount:
class CreditAccount extends Account {
private int limit;
public CreditAccount() {
super();
}
public CreditAccount(double bal, String id, double inte) { //How can I add local variable limit to this???
super(bal, id, inte);
}
public void setLimit(int limit) {
this.limit = limit;
}
#Override
public String getAccountId() {
return accountId;
}
#Override
public double getInterest(){
return interest;
}
#Override
public double getBalance() {
return balance;
}
}
in main:
System.out.print("Savings or Credit (S/C): ");
answer = input.next();
if (null != answer) switch (answer) {
case "S":
case "s":{
System.out.print("Amount to deposit: ");
double amount = input.nextDouble();
System.out.print("Interest: ");
double interest = input.nextDouble();
SavingsAccount savingsAccount = new SavingsAccount(amount, accountId, interest);
newCustomer.addAccount(savingsAccount);
bank.addCustomer(newCustomer);
break;
}
case "C":
case "c":{
System.out.print("Amount to deposit: ");
double amount = input.nextDouble();
System.out.println("Interest: ");
double interest = input.nextDouble();
CreditAccount creditAccount = new CreditAccount(amount, accountId, interest);
newCustomer.addAccount(creditAccount);
bank.addCustomer(newCustomer);
break;
}
default:
System.out.println("invalid answer");
break;
}
To answer your questions without giving your assignment away...
1) I need help with how constructor in CreditAccount looks like. How can I add local variable limit to the constructor?
I suppose you're confused about "having" to implement the constructor of the base. Well, that doesn't prevent you from providing one specific to the needs of the sub.
public CreditAccount(..., double limit) {
//call the super from this
this.limit = limit;
}
Is it better (easier) if I have a variable limit in base class instead, and let SavingsAccount Always set it to be zero, while CreditAccount let the user set the limit?
Better; nope. Easier; that's subjective. Is it easier to set an untold number of sub class' needless variable easier than not including it in the first place?
Easier isn't a factor that overrides good design. The whole point of all this is providing nice little data holders void of clutter. On top of that, it just doesn't seem right; does it; what does your gut say?
My teacher says since SavingsAccount and CreditAccount are almost the same, #Override are exactly the same, he recommends me to implement those methods in base class (Account). How will the code look like if I do that?
As opposed to the abstract class leaving the methods unimplemented, implement them. Put the simple getters inside the abstract class and remove them from the subs. The resulting code would look something like...
public CreditAccount ... {
protected double limit;
//those constructors you need
public double getLimit() { ... }
}
...for starters.

Method Retrieval and Inheritance Confusion

Ok,so I am getting a lot of trouble, I am still learning Java and my book has set me a task that I find common over the net, the part that I am stuck on is...
I must create a bank account program, an account holder is given a savings account (which has an interest rate and no overdraft facility), and a checking account (which has an overfraft facility of £100 and no interest).
I am not implementing the overdraft yet and am only half way to getting the withdraw and deposit function ready but my question is with the interest, I have defined in my superclass the savings account balance and the checking account balance so when working out my interest in the savings account class I cannot reference savebalance as I have made it private. I am trying to use the set.name method but i am clearly doing it wrong....
A big smile and a thank you for any one who can help or give advice!
Superclass is as follows:
public class BankDetails
{
private String customer;
private String accountno;
private double savebalance;
private double checkbalance;
//Constructor Methods
public BankDetails(String customerIn, String accountnoIn, double savebalanceIn, double checkbalanceIn)
{
customer = customerIn;
accountno = accountnoIn;
savebalance = savebalanceIn;
checkbalance = checkbalanceIn;
}
// Get name
public String getcustomername()
{
return (customer);
}
// Get account number
public String getaccountnumber()
{
return (accountno);
}
public double getcheckbalanceamount()
{
return (checkbalance);
}
public double getsavebalanceamount()
{
return (savebalance);
}
public void savewithdraw(double savewithdrawAmountIn)
{
savebalance = savebalance - savewithdrawAmountIn;
}
public void checkwithdraw(double checkwithdrawAmountIn)
{
checkbalance = checkbalance - checkwithdrawAmountIn;
}
public void savedeposit(double savedepositAmountIn)
{
savebalance = savebalance - savedepositAmountIn;
}
public void checkdeposit(double checkdepositAmountIn)
{
checkbalance = checkbalance - checkdepositAmountIn;
}
} // End Class BankDetails
Sub Class is as follows:
import java.util.*;
public class Savings extends BankDetails
{
private String saveaccount;
private double interest;
public Savings(String customerIn, String accountnoIn, float interestIn,
String saveaccountIn, double savebalanceIn)
{
super (customerIn, accountnoIn, savebalanceIn, interestIn);
saveaccount = saveaccountIn;
interest = interestIn;
}
public String getsaveaccountno()
{
return (saveaccount);
}
public double getinterestamount()
{
return (interest);
}
public void interestamount(String[] args)
{
BankDetails.getsavebalanceamount(savebalance);
interest = (savebalance / 100) * 1.75;
}
}
Use the superclass's getSaveBalance() method to access the balance (which is suspiciously-named, since you have a savings account class, but keep the balance elsewhere).
(Currently it's getsavebalanceamount(), I assume a renaming to keep with Java conventions.)
I'd recommend using consistent CamelCase when naming your getters and setters, e.g., getInterestAmount(), getSaveAccountNo(), etc.
I recommend against commenting simple getters/setters, but if you do, use Javadoc conventions, e.g.:
/** Returns current savings account balance. */
public double getSaveBalance() { ... etc ... }
I also recommend avoid unnecessary parentheses, as currently in your getters, e.g.:
public double getSaveBalance() {
return saveBalance; // No parens required.
}
I suggest you do something like this,
interface Account{
int getAccountNumber();
float getBalance();
}
public class SavingAccount implements Account, Interest{
int accountNumber;
public int getAccountNumber(){
return accountNumber;
}
float balance;
public float getBalance(){
return balance;
}
float savingInterestRate;
public float getInterestRate(){
return savingInterestRate;
}
}
public class CheckingAccount implements Account, OverDraft{
int accountNumber;
public int getAccountNumber(){
return accountNumber;
}
float balance;
public float getBalance(){
return balance;
}
}
interface Interest{
float getInterestRate();
}
interface OverDraft{
....
}

Categories

Resources