1 / 52

Introduction to Inheritance in Object-Oriented Programming

Learn about inheritance, how to inherit and override superclass methods, invoke superclass constructors, and understand the common superclass Object and its toString method.

mquigley
Télécharger la présentation

Introduction to Inheritance in Object-Oriented Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COMP 121 Week 3: Inheritance

  2. Objectives • To learn about inheritance • To understand how to inherit and override superclass methods • To be able to invoke superclass constructors • To understand the common superclass Object and to override its toString method

  3. Introduction to Inheritance • Inheritance • Used with object types that have a certain amount of commonality • Mountain bikes, racing bikes, road bikes, and recumbent bikes all share characteristics common to bicycles • Squares, triangles, rectangles, and octagons all share characteristics common to polygons • Deans, professors, administrators, and technical support personnel all share characteristics common to university employees • Surgeons, family doctors, pediatricians, heart specialists all share characteristics common to doctors • Savings accounts, checking accounts, money market accounts all share characteristics common to bank accounts

  4. Introduction to Inheritance • Inheritance relationship • Mountain bike inherits from bicycle • Triangle inherits from polygon • Professor inherits from university employee • Pediatrician inherits from doctor • Savings account inherits from bank account • Classes are extended by adding methods and fields • Savings account is a bank account with interest • Instance field would be added for the interest rate • Method would be added to add interest to the account

  5. Inheritance vs. Implementing an Interface • Inheriting from class is not the same as implementing an interface • Subclass inherits behavior and state • Like interfaces, one advantage of inheritance is code reuse Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  6. Inheritance Diagram • Every class extends the Object class either directly or indirectly Inheritance Inheritance Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  7. Inheritance Diagram (BlueJ) Inheritance

  8. UML Diagram (BlueJ) Uses Is-A Inheritance

  9. Inheritance Syntax class SubclassName extends SuperclassName{ methods    instance fields } • The extended class is called the superclass • The extending class is called the subclass Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  10. Question: • If the class Car extends Vehicle, which is the subclass and which is the superclass? Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  11. Subclass versus Superclass Superclass Subclass

  12. Inheritance Example public class SavingsAccount extends BankAccount { // Fields and methods unique to a SavingsAccount … } • BankAccount is the superclass • SavingsAccount is the subclass • SavingsAccount automatically inherits all methods and instance fields of BankAccount Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  13. Subclass Fields and Methods • In subclass: • Add new instance fields and methods • Change or override methods public class SavingsAccount extends BankAccount { public SavingsAccount(double rate) { interestRate = rate; } public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } private double interestRate; } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  14. Subclass Object • SavingsAccount object inherits the balance instance field from BankAccount • Additional instance field is interestRate Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  15. Encapsulation and Inheritance public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } • Encapsulation • addInterest calls getBalance rather than updating the balance field of the superclass (field is private) • addInterest calls getBalance without specifying the implicit parameter • Call applies to the same object (this) Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  16. Inheritance Hierarchies • Sets of classes can form complex inheritance hierarchies Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  17. Inheritance Hierarchies: Swing Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  18. Hierarchy of Bank Accounts • Consider a bank that offers its customers the following account types: • Checking account: no interest; small number of free transactions per month, additional transactions are charged a small fee • Savings account: earns interest that compounds monthly Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  19. Hierarchy of Bank Accounts Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  20. Hierarchy of Bank Accounts Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  21. Subclass vs. Superclass Methods • All bank accounts support the getBalance method • All bank accounts support the deposit and withdraw methods, but the implementations differ (checking account needs to count transactions) • Checking account needs a method deductFees • Savings account needs a method addInterest Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  22. Overriding vs. Inheriting Methods • Overriding a method • Supply a different implementation of a method that exists in the superclass • Must have same signature (same name and same parameter types) • If method is called on an object of the subclass type, the overriding method is executed Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  23. Overriding vs. Inheriting Methods • Inheriting a method (behavior) • Don't supply a new implementation of a method that exists in superclass • Superclass method can be called on the subclass objects Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  24. Defining New Methods • Add a method • Supply a new method that doesn't exist in the superclass • New method can be called only on subclass objects Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  25. Inheriting Instance Fields • Can't override fields • All fields from the superclass are automatically inherited • New fields that don't exist in the superclass can be added to the subclass Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  26. Inheriting Instance Fields • What if you define a new field with the same name as a superclass field? • Each object would have two instance fields of the same name • Fields can hold different values • Legal but extremely undesirable • DON’T DO IT!!! Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  27. CheckingAccount Implementation • Overrides deposit and withdraw to increment the transaction count public class CheckingAccount extends BankAccount { public void deposit(double amount) {. . .} public void withdraw(double amount) {. . .} public void deductFees() {. . .} // new method private int transactionCount; // new instance field } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  28. CheckingAccount Implementation • Each CheckingAccount object has two instance fields: • balance (inherited from BankAccount) • transactionCount (new to CheckingAccount) Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  29. CheckingAccount Implementation • You can apply four methods to CheckingAccount objects: • getBalance() (inherited from BankAccount) • deposit(double amount) (overrides BankAccount method) • withdraw(double amount) (overrides BankAccount method) • deductFees() (new to CheckingAccount) Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  30. Accessing Private Fields in Superclass • Consider deposit method of CheckingAccount • Can't just add amount to balance • balance is a private field of the superclass public void deposit(double amount) { transactionCount++; // now add amount to balance . . . } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  31. Accessing Private Fields in Superclass • A subclass has no access to private fields of its superclass • Subclass must use public interface So how can we add the amount to the balance? Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  32. Invoking a Super Class Method • Can't just calldeposit(amount)in deposit method of CheckingAccount • That is the same as this.deposit(amount) • Calls the same method (infinite loop) • Instead, invoke superclass methodsuper.deposit(amount) Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  33. Invoking a Superclass Method public void deposit(double amount) { // Increment the transaction count transactionCount++; // Now add amount to balance super.deposit(amount); } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  34. Subclass Construction • The super keyword is also used to call a constructor • super followed by parameters in parentheses indicates a call to the superclass constructor • Must be the first statement in subclass constructor • If subclass constructor doesn't explicitly call superclass constructor, the default superclass constructor is used • Default constructor -- constructor with no parameters • If all superclass constructors require parameters, it’s a compile error error Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  35. Subclass Construction public class CheckingAccount extends BankAccount { public CheckingAccount(double initialBalance) { // Construct superclass super(initialBalance); // Initialize transaction count transactionCount = 0; } . . . } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  36. Converting Between Subclass and Superclass Types • Can convert a subclass reference to superclass reference SavingsAccount collegeFund = new SavingsAccount(10); BankAccount anAccount = collegeFund; Object anObject = collegeFund; • The three object references stored in collegeFund, anAccount, and anObject all refer to the same object of type SavingsAccount Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  37. Converting Between Subclass and Superclass Types Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  38. Converting Between Subclass and Superclass Types • Superclass references don't know about methods in the subclass • When you convert a subclass object to its superclass type • The value of the reference stays the same (actual memory location of the object) • Less information is known about the object anAccount.deposit(1000); // OK anAccount.addInterest(); // Not OK Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  39. Converting Between Subclass and Superclass Types • Why would anyone want to know less about an object? • Reuse code that knows about the superclass but not the subclass: • Can be used to transfer money from any type of BankAccount public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  40. Converting Between Subclass and Superclass Types • Occasionally you need to convert from a superclass reference to a subclass reference • If object types are unrelated (not a superclass/ subclass relationship), an exception is thrown at runtime BankAccount anAccount = (BankAccount) anObject; Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  41. instanceof operator • Tests whether an object belongs to a particular type • Returns true if the object on the left hand side of the operator is an instance of the type on the right hand side of the operator • Otherwise, returns false if (anObject instanceof BankAccount) { BankAccount anAccount = (BankAccount) anObject; . . . } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  42. Object: The Cosmic Superclass • All classes defined without an explicit extends clause automatically extend Object Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  43. Useful Methods in the Object Class • String toString() • boolean equals(Object otherObject) • Object clone() • Good idea to override these methods in your classes • Will not be overriding clone() in this course Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  44. Overriding the toString Method • Returns a string representation of the object • Useful for debugging Rectangle box = new Rectangle(5, 10, 20, 30); String s = box.toString(); // Sets s to "java.awt.Rectangle[x=5,y=10,width=20,height=30]" Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  45. Overriding the toString Method • toString is called whenever you concatenate a string with an object: • Object.toString default behavior is to print the class name and the hash code of the object "box=" + box; // Result: "box=java.awt.Rectangle[x=5,y=10,width=20,height=30]" BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to something like "BankAccount@d24606bf" Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  46. Overriding the toString Method public String toString() { return "BankAccount[balance=" + balance + "]"; } • In BankAccount: • Converts BankAccount object to a String • Used by System.out.println BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to "BankAccount[balance=5000]" Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  47. Inheritance and toString Method • toString method often returns the class name and the names and values of the instance fields in a class • In a superclass, to be usable by subclasses, get the class name instead of hard-coding it • For example, in BankAccount: public String toString() { return getClass().getName()+"[balance =" + balance + "]";} Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  48. Inheritance and toString Method • In a subclass, first get the string that represents the superclass, then add the subclass information • For example, in SavingsAccount: public String toString() { return super.toString() + "[interestRate = " + interestRate + "]"; } Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  49. Summary • Inheritance is used to extend existing classes by adding methods and fields • The more general class is called the superclass • The more specialized class that inherits from the superclass is called the subclass • The subclass inherits both state and behavior from the superclass • Code reuse is one advantage of inheritance Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

  50. Summary (continued) • Methods in the superclass can be changed or overridden in the subclass • A subclass cannot access the private fields of the superclass • The super keyword is used to call a method of the superclass • The super keyword may also be used as the first statement of the subclass constructor to call the superclass constructor Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

More Related