CSC 205 Java Programming II Inheritance
Topics What is Inheritance? Subclassing in Java When not to use inheritance? Overriding
Hierarchy Hierarchy is a ranking or ordering of abstractions Two most important hierarchies The “part-of” relationship, or aggregation The “is-a” relationship , or inheritance Inheritance, also known as subclassing Single inheritance: the only legal way in Java Multiple inheritance: supported in C++
Hierarchy: “is-a” relationship
Illustrating Inheritance Account specialization generalization SavingsAccount CheckingAccount
Subclassing in Java A subclass SavingsAccount: public class SavingsAccount extends Account { private double interestRate; public double getInterestRate() { return interestRate; } public void setInterestRate(double rate) { interestRate = rate;
Writing a Subclass A SavingsAccount object will contain two variables: balance, and interestRate Inherited from Account
Writing a Subclass Methods that can be applied to SavingsAccount objects: getInterestRate setInterestRate deposit (inherited) withdraw (inherited) getBalance (inherited) close (inherited)
When Not to Use Inheritance? Inheritance is one from many kinds of relationships among classes Don’t define an Account class by extending a Money class just because they are related Other relationships are available Aggregation: the “has-a” relationship Dependency: the “use” relationship
Hierarchy: “part-of” relationship
Aggregation & Composition University aggregation composition Student Department
The protected Access Modifier Four levels of accessibility for class members public protected (package or default) private The protected modifier allows for a subclass to access a member in its superclass
Overriding A subclass can replace some of its inherited behavior by overriding The toString() method Although a class method may not be overridden, it may be hidden