1Chapter 13 Chapter 13 --InheritanceInheritanceGoalsGoalsTo learn about inheritance To learn about inheritance To understand how to inherit and override To understand how to inherit and override superclasssuperclassmethods methods To be able to invoke To be able to invoke superclasssuperclassconstructors constructors To learn about protected and package access To learn about protected and package access control control To understand the common To understand the common superclasssuperclassObject Object and to override its and to override its toStringtoStringand equals methods and equals methods In OOP languages, new classes can be derived In OOP languages, new classes can be derived from an existing class.from an existing class.Why?Why?organizes related classesorganizes related classesreduces code redundancyreduces code redundancyincreases code reuseincreases code reuseenables enables polymorphic polymorphic referencesreferences13.1 Introduction to Inheritance13.1 Introduction to InheritanceInheritance: extend classes by adding methods Inheritance: extend classes by adding methods and fields and fields Example: Savings account is a bank account Example: Savings account is a bank account with interest with interest class class SavingsAccountSavingsAccountextends extends BankAccountBankAccount{{new methodsnew methodsnew instance fieldsnew instance fields} } SavingsAccountSavingsAccountautomatically inherits all methods and automatically inherits all methods and instance fields of instance fields of BankAccountBankAccountSavingsAccountSavingsAccountcollegeFundcollegeFund= new SavingsAccount(10);= new SavingsAccount(10);// Savings account with 10% interest // Savings account with 10% interest collegeFund.deposit(500); collegeFund.deposit(500); // OK to use // OK to use BankAccountBankAccountmethod with method with SavingsAccountSavingsAccount// object// objectOriginal/base class is known as the Original/base class is known as the superclasssuperclass((BankAccountBankAccount))extending class is the extending class is the subclasssubclass((SavingsAccountSavingsAccount) )2Every class extends the Every class extends the ObjectObjectclass either class either directly or indirectly directly or indirectly Inheritance Inheritance vsvsInterfaceInterfaceInheriting from class IS NOT the same as Inheriting from class IS NOT the same as implementing interfaceimplementing interfacesubclass inherits behavior and statesubclass inherits behavior and stateInterfaces have no state or defined behavior Interfaces have no state or defined behavior (only names of shared methods)(only names of shared methods)Code ReuseCode ReuseOne advantage of inheritance is code reuse One advantage of inheritance is code reuse Not Not ““reinventing the wheelreinventing the wheel””Already have a class that does some base functions, Already have a class that does some base functions, why not just build up on it?why not just build up on it?Deposit, withdraw, Deposit, withdraw, getBalancegetBalancecommon among all common among all accountsaccountsIn subclass, specify added instance fields, added In subclass, specify added instance fields, added methods, and changed or overridden methods methods, and changed or overridden methods Inheritance takes care of what is common, you define what Inheritance takes care of what is common, you define what is differentis differentpublic class public class SavingsAccountSavingsAccountextends extends BankAccountBankAccount{{private double private double interestRateinterestRate; ; public public SavingsAccount(doubleSavingsAccount(doublerate) {rate) {interestRateinterestRate= rate; = rate; }}public void public void addInterestaddInterest() { () { double interest = double interest = getBalancegetBalance() * () * interestRateinterestRate/ / 100; 100; deposit(interestdeposit(interest); ); }}}}EncapsulationEncapsulationWhy do we call Why do we call getBalancegetBalance??double interest = double interest = getBalancegetBalance() * () * interestRateinterestRate/ 100;/ 100;Encapsulation: Encapsulation: addInterestaddInterestcalls calls getBalancegetBalancebecause because balancebalancefield of the field of the superclasssuperclassis is privateprivateCannot access private members of another class Cannot access private members of another class (even a subclass!)(even a subclass!)SavingsAccountSavingsAccountobject inherits the object inherits the balance balance instance field from instance field from BankAccountBankAccount, and gains one , and gains one additional instance field:additional instance field:interestRateinterestRate3Note that Note that addInterestaddInterestcalls calls getBalancegetBalancewithout without specifying an implicit parameter (the calls apply specifying an implicit parameter (the calls apply to the same object) to the same object) Means the call to is Means the call to is getBalancegetBalanceis applied to the is applied to the same object as the object that called same object as the object that called addInterestaddInterestSyntaxSyntaxclass class SubclassNameSubclassNameextends extends SuperclassNameSuperclassName{ { methods methods instance fields instance fields } } 13.2 Inheritance Hierarchies13.2 Inheritance HierarchiesInheritance is a way to categorizeInheritance is a way to categorizeIn real world, categories often use hierarchiesIn real world, categories often use hierarchiesGeneric items yield more specific itemsGeneric items yield more specific itemsBird Bird Robin, Blue Jay, Cardinal, etc.Robin, Blue Jay, Cardinal, etc.Sets of classes can form complex Sets of classes can form complex inheritance inheritance hierarchies hierarchies HierarchyHierarchyWhat is the common set of features?What is the common set of features?SuperclassSuperclassThere are all birds There are all birds class Bird{class Bird{……}}ISA HierarchyISA HierarchyWhat is at the top of every hierarchy?What is at the top of every hierarchy?ExampleExampleConsider a bank that offers its customers the Consider a bank that offers its customers the following account types: following account types: Checking account: no interest; small number of free Checking account: no interest; small number of free transactions per month,
View Full Document