Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 205 Java Programming II

Similar presentations


Presentation on theme: "CSC 205 Java Programming II"— Presentation transcript:

1 CSC 205 Java Programming II
Inheritance

2 Topics What is Inheritance? Subclassing in Java
When not to use inheritance? Overriding

3 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++

4 Hierarchy: “is-a” relationship

5 Illustrating Inheritance
Account specialization generalization SavingsAccount CheckingAccount

6 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;

7 Writing a Subclass A SavingsAccount object will contain two variables:
balance, and interestRate Inherited from Account

8 Writing a Subclass Methods that can be applied to SavingsAccount objects: getInterestRate setInterestRate deposit (inherited) withdraw (inherited) getBalance (inherited) close (inherited)

9 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

10 Hierarchy: “part-of” relationship

11 Aggregation & Composition
University aggregation composition Student Department

12 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

13 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


Download ppt "CSC 205 Java Programming II"

Similar presentations


Ads by Google