Presentation is loading. Please wait.

Presentation is loading. Please wait.

Phil Tayco Slide version 1.1 Created Oct 30, 2017

Similar presentations


Presentation on theme: "Phil Tayco Slide version 1.1 Created Oct 30, 2017"— Presentation transcript:

1 Phil Tayco Slide version 1.1 Created Oct 30, 2017
Inheritance Phil Tayco Slide version 1.1 Created Oct 30, 2017

2 Practice Before examining the next topic, let’s practice building a couple of classes using the concepts learned so far Problem statement: Write a program that manages customer savings account information Customers are identified by first and last name and numeric id Savings accounts are identified with an alphanumeric account id and contain a current balance and interest rate Customers can have up to 5 accounts The program must be able to identify the date when customers created each of their accounts We can work on creating a front end user interface for this program later – for now, let’s look at designing and testing the classes to support this program

3 Observations One of the strong benefits of OO design is the flexibility in maintaining code as requirements change What are some ways the program we just wrote could change? Additional information about customers (address, gender, date of birth, etc.) Requiring the need to determine if a customer has any accounts over a year old Notice also that this particular program is dealing with savings accounts What other types of accounts exist? How are these accounts differentiated?

4 Account Types Savings accounts Checking accounts
In the practice example, they have an id, balance, interest rate and date created Withdrawing too many times may not be allowed Applying interest on the balance can occur once a month Projected balances after a given amount of time are usually requested Checking accounts Have the same properties as savings accounts plus another id for routing numbers and no interest rate Withdrawing is conducted often without penalty Long term savings accounts Also the same properties as savings accounts plus a period of time when withdrawing is not allowed and no interest rate Instead of an interest rate, a bonus is calculated at creation to be applied when the savings period ends, at which point the account changes to a checking account

5 Account Types OO design is all about code reuse – the types of accounts here suggest there are properties and functions that can be reused While creating multiple objects to reuse class code, the class code itself is fixed as the template The template of code actually differs with the different types of accounts The tendency at first is to create objects of a certain class and then based on the way the object was created, tailor the usage of the class code as needed This is not quite correct because objects represent instances of specific types What we have here are different types that can be instantiated

6 Different Classes If we have different types, then we can simply create different classes for each type public class SavingsAccount { private int id; private double interestRate; private double balance; private DateTime dateCreated; private int withdrawCount; } public class CheckingAccount private Date dateCreated; private String routingNumber;

7 Different Classes Notice the similarities between these classes – both share id, date created and balance Notice the differences: Savings accounts have an interest rate and withdraw count Checking accounts have routing numbers Set/get, constructors and toString methods can easily be derived individually with each class – notice that for properties that are common between classes, code for those specific properties are likely to be the same If we examine the similar properties, they are id, date created and balance – what type of class could be represented with these properties?

8 A Higher Level Class The common properties all have to do with some kind of Account: public class Account { private int id; private double balance; private Date dateCreated; } Conceptually, this is an accurate model of a more general type of Account as all Accounts at least have an id, balance and creation date Savings and Checking Accounts are more specific designs of an Account To view another way, a Savings or a Checking Account is a type of Account OO languages capture this by allowing classes to reuse properties and methods from other classes

9 A Higher Level Class The Account class itself is just like any other class Account objects can be instanatiated Set/get, constructors and toString methods are as normal Creating the Account class from the existing SavingsAccount class is a nice baseline, but code specific to SavingsAccount must be removed after copied to Account Account sets the foundation for other types of Accounts

10 Subclasses public class CheckingAccount extends Account { private String routingNumber; } public class SavingsAccount extends Account private double interestRate; Here, a CheckingAccount has all the properties and functions defined in an Account as well its own routing number A SavingsAccount has all the properties and functions defined in an Account as well as its own interest rate Savings and Checking are considered “subclasses” of the more general Account class Subclasses “inherit” the design of the parent/super class Subclass code is simplified to focus on code specific to the characteristics of that subclass

11 Inheritance public class Account { public double getBalance() return balance; } In this example, getBalance is defined in the parent class Account An object created as an Account can use this function as normal Because Savings and Checking inherit from Account, objects of those types can also use getBalance Savings and Checking do not need to redefine getBalance (though there may be situations when redefining an inherited function is necessary…)

12 Inheritance public static void main(String[] args) { Account a = new Account(); CheckingAccount c = new CheckingAccount(); SavingsAccount s = new SavingsAccount(); System.out.println(a.getBalance()); System.out.println(c.getBalance()); System.out.println(s.getBalance()); } Because Savings and Checking inherit from Account, objects of those types can also use getBalance The functionality is defined in Account and is being reused as part of the definition of Checking and Savings Main doesn’t even know this reuse of code through inheritance is even happening, nor should it! getInterestRate() in SavingsAccount would likely exist. Would it exist in CheckingAccount? Why or why not?

13 Inheritance Hierarchy
Graphically, classes using inheritance are usually depicted as follows The arrows pointing up signify that Checking and Savings are subclasses of Account Hierarchies are usually described this way to emphasize the super/sub class relationship similar to a parent/child As one goes up the inheritance hierarchy, classes higher up are conceptually more “general” while classes going down are conceptually more “specialized” We can have more classes like Long Term Savings defined to inherit from Account – it can also be a child of Savings! Account CheckingAccount SavingsAccount

14 Inheritance Hierarchy
Adding the properties of the classes to the picture shows where definitions are owned and reused The properties in Account are implicitly included in Checking and Savings Account String id double balance DateTime dateCreated CheckingAccount String routingNumber SavingsAccount double interestRate int withdrawCount

15 Private Access Higher level classes may still have their properties defined as private as we saw for id, balance and date created for Account Private means no code outside the class can see these properties – this still applies to subclasses public class SavingsAccount extends Account { public double applyInterest() balance += (balance * interestRate); } At first, this appears correct since balance and interestRate are properties of a SavingsAccount Balance, though, is defined as private in Account – even though SavingsAccount inherits from Account, if the property is private, SavingsAccount still cannot directly access it

16 Private Access To remedy this, many languages allow properties to be protected: public class Account { protected int id; protected double balance; protected Date dateCreated; } Protected properties are considered private for other objects and code outside the class Protected properties can be directly accessed only within subclasses on its inheritance hierarchy Pure OO designers mark properties as private as often as possible as a stand alone class should be designed without knowing how it will specifically be used If a class is likely to have subclasses, protecting properties can be helpful

17 Constructors The purpose of constructor functions is to initialize all properties of an object when it is created If a subclass is using inheritance, it may not be able to access properties in the superclass if they are private As a whole, though, the subclass will want to do something with the properties it inherits from the superclass (i.e. if a SavingsAccount wants to instantiate an object with a known ID and balance, it will want to initialize them appropriately) SavingsAccount may only have direct access to its own properties public SavingsAccount(String i, double b, double ir { interestRate = ir; withdrawCount = 0; // What do we do with i and b for id and balance? }

18 Constructors Since we are in the SavingsAccount constructor, we know we are at a point where we need to perform constructor functionality with the Account level properties We can do this by calling the Account constructor using the “super()” method public SavingsAccount(String i, double b, double ir { super(i, b); interestRate = ir; withdrawCount = 0; } “super” calls the parent constructor with the matching signature (in this case, the Account constructor that takes a String and double) “super” must be the first line in the subclass constructor If superclass properties are protected, using super may not be necessary – using “super” though promotes reuse of code, particularly if the super class constructor is complex

19 Inheriting Methods Reusing methods is a primary benefit to using inheritance with classes and subclasses In many situations, though, methods in subclasses may want to redefine the inherited method functionality Note in the Account class, the withdraw method simply subtracts the amount from the balance as long as the amount doesn’t exceed the current balance public boolean withdraw(double amount) { if (amount > balance) return false; balance -= amount; return true; }

20 Inheriting Methods The withdraw method in the SavingsAccount class, however, may define withdrawing differently In this example, withdrawing is only permitted if the SavingsAccount has not had more than 3 withdraws attempted. The code for that is as follows: public boolean withdraw(double amount) { if (amount > balance || withdrawCount == 3) return false; balance -= amount; withdrawCount++; return true; }

21 Inheriting Methods The withdraw method has the exact same signature as the withdraw method defined in Account Even though the signatures are the same, because this method is defined at the SavingsAccount level, it takes precedence when SavingsAccount objects call the withdraw method Methods in subclasses “override” methods in the superclass with matching signatures Method overrides allow subclasses to redefine functionality inherited from the superclasses Notice the SavingsAccount withdraw method uses properties specific to the SavingsAccount (withdrawCount) – this is often the case with method overrides

22 Inheriting Methods Java also allows for a special notation with overrides: @Override public boolean withdraw(double amount) { if (amount > balance || withdrawCount == 3) return false; balance -= amount; withdrawCount++; return true; } statement specifically designates the method is overriding a method from the parent class. This is considered good practice: The compiler ensures the method is overriding a matching signature from the parent. This helps make sure your code is as you intended to design The code is more readable by specifically calling out that an override is occurring

23 Inheritance Summary Class design is intended to model real world scenarios and promote code reuse, maintenance and readability Class relationships and similarities between them generate opportunities for code reuse Classes individually are designed by identifying their properties and behaviors – what does it have and what do we want it to be able to do Classes collectively can define relationships through identifying if one class is a type of another – a Savings Account is a type of Account The higher level class contains the common properties and methods that all subclass types can reuse and define a more general type of information Subclasses add on to these types defining a more specific type of that data and add/override properties and methods Objects of super and subclasses are instantiated as normal, sometimes not even aware that inheritance is in use In addition to straight code reuse, the inheritance hierarchy also sets up the foundation for a more powerful use of super and subclasses…

24 Exercise 6 The class code worked on today defines an Account class and SavingsAccount class along with some other supporting classes and a test program Add to the project a “CheckingAccount” class and a “LongTermSavingsAccount” class that each inherit from Account and supports the following: Checking accounts have the same properties as an Account and also have a 10-digit routing number (that could start with a 0 and is included in its identification) Checking accounts can also have a negative balance, but as soon as that happens, the account is flagged as negative and does not allow for further withdrawals. More funds can be added to the account to get it out of the negative state Long term savings accounts have the same properties as an Account and a flag that indicates whether or not it is enabled for deposit and withdraw transactions If the flag is set to false, no deposits or withdraws are allowed If the flag is set to true, only withdraws are allowed. Deposits remain disabled For both classes, ensure all the appropriate set/get, constructors and toString methods are defined For the main program, ensure all methods and object instantiations are tested


Download ppt "Phil Tayco Slide version 1.1 Created Oct 30, 2017"

Similar presentations


Ads by Google