Unformatted text preview:

Week 4Inheritance and PolymorphismCS 180Sunil PrabhakarDepartment of Computer Science Purdue UniversityObjectivesUnderstand Inheritanceexpressing inheritance: extends visibility and inheritance: protectedoverriding, final constructors and inheritance: superPolymorphismpolymorphic messagesinstanceof operatorabstract classes & methods: abstract23IntroductionInheritance and polymorphism are key concepts of Object Oriented Programming.Inheritance facilitates the reuse of code.A subclass inherits members (data and methods) from all its ancestor classes.The subclass can add more functionality to the class or replace some functionality that it inherits.Polymorphism simplifies code by automatically using the appropriate method for a given object.Polymorphism also makes it easy to extend code.Inheritance45Sample applicationBanking Example:There are two types of accounts: checking and savings.All accounts have a number, and an owner (with name, and a Social Security number), and balance.There are different rules for interest and minimum balance for checking accounts and savings accounts.How should we model this application?Two classes, one for each type of account? Have to repeat code for common parts.can lead to inconsistencies, harder to maintain.Create three classes: Account; SavingsAccount, and CheckingAccount6InheritanceA superclass corresponds to a general class, and a subclass is a specialization of the superclass.E.g. Account, Checking, Savings.Behavior and data common to the subclasses is often available in the superclass.E.g. Account number, owner name, data opened.Each subclass provides behavior and data that is relevant only to the subclass.E.g. Minimum balance for checking a/c, interest rate and computation for savings account.The common behavior is implemented once in the superclass and automatically inherited by the subclasses.InheritanceIn order to inherit the data and code from a class , we have to create a subclass of that class using the extends keyword.public class SavingsAccount extends Account {SavingsAccount will inherit the data members and methods of Account.SavingsAccount is a sub (child, or derived) class; Account is a super (parent or base) class.A parent (of a parent ...) is an ancestor class. A child (of a child ...) is a descendant class.78The Account classclass Account { protected String ownerName; protected int socialSecNum; protected float balance; public Account() { this(“Unknown”, 0, 0.0); } public Account(String name, int ssn) { this(name, ssn, 0.0); } public Account(String name, int ssn, float bal) { ownerName = name; socialSecNum = ssn; balance = bal; } public String getName( ) { return ownerName; } public String getSsn( ) { return socialSecNum; } public float getBalance() { return balance; } public void setName(String newName) { ownerName = newName; } public void accrueInterest() { System.out.println(“No interest”); }public void deposit(float amount) { balance += amount; }}9Savings Accountclass SavingsAccount extends Account{ protected static final float MIN_BALANCE=100.0; protected static final float OVERDRAW_LIMIT=-1000.0; protected static final float INT_RATE=5.0; public void accrueInterest() { balance *= 1 + INT_RATE/100.0; } public void withdraw(float amount) { float temp; temp = balance - amount;if (temp >= OVERDRAW_LIMIT) balance = temp; else System.out.println(“Insufficient funds”); }}10Checking Accountclass CheckingAccount extends Account{ protected static final float MIN_INT_BALANCE=100.0; protected static final float INT_RATE=1.0; public void accrueInterest() {if (balance > MIN_INT_BALANCE) balance *= 1 + INT_RATE/100.0; } public void withdraw(float amount) { float temp; temp = balance - amount;if (temp >= 0) balance = temp; else System.out.println(“Insufficient funds”); }}Visibility1112The visibility modifierspublic data members and methods are accessible to everyone.private data members and methods are accessible only to instances of the class.protected data members and methods are accessible only to instances of the class and descendant classesprotected is similar to:public for descendant classesprivate for any other class13Visibility (unrelated class)class Test {Sup sup = new Sup();Sub sub = new Sub(); sup.a = 5;sup.b = 5;sup.c = 5;sub.a = 5;sub.b = 5;sub.c = 5;sub.d = 5;sub.e = 5;sub.f = 5; } class Sup {public int a;protected int b;private int c;}class Sub extends Sup {public int d;protected int e;private int f;}From an unrelated class, only public members are visible.14Visibility (related class)class Sup {public int a;protected int b;private int c;}class Sub extends Sup {public int d;protected int e;private int f;public void methodA(){a=5;b=5;c=5;d=5;e=5;f=5;}}From a descendant class, only private members of ancestors are hidden.15Visibility (static members)class Test {Sup sup = new Sup();Sub sub = new Sub(); sup.a = 5;sup.b = 5;sup.c = 5;sub.a = 5;sub.b = 5;sub.c = 5;sub.d = 5;sub.e = 5;sub.f = 5; } class Sup {public static int a;protected static int b;private static int c;}class Sub extends Sup {public static int d;protected static int e;private static int f;}Same rules for class (static) members.16Visibility (static members)class Sup {public static int a;protected static int b;private static int c;}class Sub extends Sup {public int d;protected int e;private int f;public void methodA(){a=5;b=5;c=5;d=5;e=5;f=5;}}Same rules for class (static) members.17Visibility (across instances)class Sup {public int a;protected int b;private int c;}class Sub extends Sup {public int d;protected int e;private int f;public void methodA(Sub s){s.a=5;s.b=5;s.c=5;s.d=5;s.e=5;s.f=5;}}An instance method has the same access to data members of any object of that class.Overriding1819OverridingAll non-private members of a class are inherited by derived classesThis includes instance and class membersA derived class may however, override an inherited methodData members can also be overridden but should be avoided since it only creates confusion.To override a method, the derived class simply defines a method with the same signature (same name, number and types of parameters)An overridden method cannot change the return type!A subclass may also


View Full Document

Purdue CS 18000 - Inheritance and Polymorphism

Download Inheritance and Polymorphism
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Inheritance and Polymorphism and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Inheritance and Polymorphism 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?