Method Retrieval and Inheritance Confusion - java

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{
....
}

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.

Exception Error in Java : How to continue?

Now, here' the problem :
How to add exceptions so that if my value is negative it would return an error.
here's my current code.
public class Account {
String name;
double balance;
public Account()
{
super();
this.name = null;
this.balance = 0;
}
public Account(String n, double b){
name = n;
balance = b;
}
}
did I do things right? so far?
edited to shorten.
1 . Create new Exception class like NegativeBalanceException
2 . Validate balance from the place where you are calling Account(String n, double b). If its -ve then throw NegativeBalanceException and right a catch block to handle it
In my opinion, this is what the exercise wants you to do:
public class Account {
/*
* If you know about private members, declare them private.
* Probably you should because the exercise asks for getter and setter.
*/
/* private */ String name;
/* private */ double balance;
public Account() {
// Useless: Java calls automatically the superclass constructor.
// super();
/*
* These are useless too, because Java initializes the class
* members to 0, false and null.
* However, this is what the exercise is asking you to do.
*/
name = null;
balance = 0;
}
public Account(String name, double balance) {
// take advantage of setters
setName(name);
setBalance(balance);
}
public void setName(String name) { this.name = name; }
public void setBalance(double balance) {
if (balance < 0)
throw new IllegalArgumentException("balance must be non-negative.");
this.balance = balance;
}
public String getName() { return name; }
public double getBalance() { return balance; }
}
You don't need to call super(); in your default constructor since you don't have superclass defined (at least I don't see that it extends something) and this method will call constructor from superclass.

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.

Why will objects now be created from my class

An error points to the word "new" when I try to compile this program. I'm trying to create 2 objects from the carOrder class and I'm havin troubles! I've had this problem with other programs before and I'm not sure why and it's killing me, please help!
import java.text.DecimalFormat;
import java.util.Scanner;
public class CarOrder
private String buyer;
private String carType;
private double cost;
private int quantity;
private boolean taxStatus;
private double discountedCost;
private double taxAmount;
// Default Constructor
public void carOrder()
{
}
// Constructor
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
buyer = buy;
carType = car;
cost = cos;
quantity = quan;
taxStatus = tax;
}
// Sets the company buying cars
public void setBuyer(String buy)
{
buyer = buy;
}
// Sets the car type being purchased
public void setCarType(String car)
{
carType = car;
}
// Sets cost of the cars being purchased
public void setCost(double cos)
{
cost = cos;
}
// Sets the quantity of cars being purchased
public void setQuantity(int quan)
{
quantity = quan;
}
// Sets tax status for the cars
public void setTaxStatus(boolean tax)
{
taxStatus = tax;
}
// Returns name of buyer to user
public String getBuyer()
{
return buyer;
}
// Returns type of car to user
public String getCarType()
{
return carType;
}
// Returns cost to user
public double getCost()
{
return cost;
}
// Returns quantity of cars to user
public int getQuantity()
{
return quantity;
}
// Returns tax status to user
public boolean getTaxStatus()
{
return taxStatus;
}
// Returns discounted cost to user
public double getDiscountedCost()
{
if (quantity > 10)
if (quantity > 20)
discountedCost = cost - cost * .10;
else
discountedCost = cost - cost * .05;
else
discountedCost = cost;
return discountedCost;
}
// Returns tax amount to users
public double getTaxAmount()
{
taxAmount = cost * .0625;
return taxAmount;
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
CarOrder speedy = new CarOrder("Speedy Rental", "Mini Cooper", 22150, 15, true);
CarOrder zip = new CarOrder("Zip Car Co.", "Ford Fusion", 27495, 6, true);
System.out.println("Enter first Buyer");
String buyer1 = keyboard.nextLine();
}
}
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
should be
public CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
Constructor's don't have a return type, not even void.
Currently, you have a method named CarOrder in your class as it has a return type as void, which voilates the rules of custructor. If you remove void, then it'd a constructor as it has the same name as your class.
Same applies to your constructor with no-argsaswell.
public void CarOrder()
should be
public CarOrder()
you are missing a "{" right after public class CarOrder ... :)
When you don't declare a constructor, Java provides a default constructor that have no arguments. As you declared CarOrder(String buy, String car, double cos, int quan, boolean tax), the default constructor is not created anymore. You made a method called carOrder, that probably was an attempt to make a constructor with no arguments, but it has two problems:
it has a return type (void) and constructor doesn't have one
the name is different from the class (cardOrder isn't the same as CarOrder, since Java is case sensitive)
If you want to make a new CarOrder() call, just add the following code:
public CarOrder() {
//insert your implementation here
}
A constructor with a return type is treated as a method by the compiler.

Categories

Resources