
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































public class BankAccount { private double balance; public BankAccount() {...} public BankAccount(double initBalance) {...} public void deposit(double amount) {...} public void withdraw(double amount) {...} public double getBalance() {...} public String toString() {...} } automatically inherits from Object if no other superclass is specified
public SavingsAccount(double initBalance, double initRate) { super (initBalance); interestRate = initRate; } public SavingsAccount(double initRate) { super (); interestRate = initRate; } must be first statement the superclass initializes balance
In BankAccount: protected double balance; In SavingsAccount: public void addInterest() { deposit( balance *interestRate); }
These methods typically do not work properly for our specific subclasses so we must override them. public boolean equals(Object obj) { SavingsAccount other = (SavingsAccount)obj; return this.interestRate == other.interestRate && this.balance == other.balance; } (assumes balance is protected in the BankAccount class) SavingsAccount class
In the equals method, we used the following cast: SavingsAccount other = (SavingsAccount)obj; What if obj is not a SavingsAccount? A ClassCastException is thrown at runtime. We can use the instanceof operator to check the object's actual type during runtime to avoid the exception.