40 likes | 164 Views
10-1 Intro Inheritance 1 of 4. Inheritance is a mechanism for enhancing existing classes. A new more specific class that has all the traits of an existing class has the capability to inherit all the data & methodology from the more general class.
E N D
10-1 Intro Inheritance 1 of 4 • Inheritance is a mechanism for enhancing existing classes. • A new more specific class that has all the traits of an existing class has the capability to inherit all the data & methodology from the more general class. • Consider a “SavingsAcct” class which pays interest on the balance. We can have “SavingsAcct” inherit from the more general “BankAcct” class without having to reinvent the wheel(reuse). • public class SavingsAcctextendsBankAcct { // new methods, overloaded/overridden methods & instance fields } • All methods & data of “BankAcct” are inherited by “SavingsAcct”. • Be aware of access privileges though! • Consider: • SavingsAccts = new SavingsAcct(3.5); • s.deposit(1000); // method from “BankAcct”! <eoln>
10-1 Intro Inheritance Cont. 2 of 4 • Terminology: • Superclass – Base class or more general class (“BankAcct”); • Subclass – Class inheriting or more specific class(“SavingsAcct”). • Every class in Java extends from the Object class. • The Object class is the lowest common denominator among all classes. • The object class has some common methods which all class objects have access to : • .toString( ) • .equals(Object obj) • The Programmer must override these methods for specific meaning!
10-1 Intro Inheritance Cont. 3 of 4 • In-Class Work: • Open “BankAcct” from Extras • Write a subclass “SavingsAcct” extending “BankAcct” with: • Instance Field: myRate • Method: addInterest( ) • Now write the client (tester) code to perform the following: • Create a new SavingsAcct reference. Rate @ 3.25% • Deposit $1000 • Calculate Interest • Deposit another $1000 • Calculate Interest • Withdraw $500 • Calculate Interest • Print the Balance
Homework I. Add another subclass CheckingAcct with the following attributes: • CheckingAcct extends BankAcct //data- myNumCks - incr whenever check is written. //myTransactions- incr whenever a transaction occurs. i.e. deposit( ), withdraw( ), … • writeCheck( ) • Call validateFunds( ) • deduct amount from balance • increment myNumCks • deductFees( ) • Charge a $0.25 fee for every 10th check written. • validateFunds( ) • Verify there are enough funds to cover check. • Charge a $5 fee if balance falls below $100. II. Write a transfer(BankAcct acct, double amt) method in BankAcct which transfers amtfrom the parameter BankAcct acct and deposits to the implicit parameter.