CHAPTER 11 INHERITANCE. CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.

Slides:



Advertisements
Similar presentations
Chapter 13 - Inheritance. Goals To learn about inheritance To learn about inheritance To understand how to inherit and override superclass methods To.
Advertisements

Inheritance INHERITANCE: extending classes by adding or redefining methods, and adding instance fields Suppose we have a class Vehicle: public class Vehicle{
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Computer Science A 9: 3/11. Inheritance Today: Inheritance (JC – CCJ ) I have to leave at 11am (but you can stay)
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Part I. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
I NHERITANCE Chapter 10. I NHERITANCE Mechanism for enhancing existing classes You need to implement a new class You have an existing class that represents.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.
Inheritance. Class Relationships Composition: A class contains objects of other class(es) (actually, references to such objects) –A “has a” relationship.
Chapter 13 Inheritance. An Introduction to Inheritance Inheritance: extend classes by adding methods and fields (variables) Example: Savings account =
CHAPTER 11 INHERITANCE CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Ten: Inheritance.
Chapter 2 – An Introduction to Objects and Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
The Java Programming Language  Simple – but abstract  Safe  Platform-independent ("write once, run anywhere")  Has a Rich growing library  Designed.
Inheritance Part III. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke.
CHAPTER 2 OBJECTS AND CLASSES Goals: To understand the concepts of classes and objects To realize the difference between objects and object references.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Object Oriented Design CSC 171 FALL 2001 LECTURE 12.
Chapter 10  Inheritance 1 Chapter 10 Inheritance.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Inheritance Motivation –Code reuse –Conceptual modeling.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
ITM 352 Class inheritance, hierarchies Lecture #.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Inheritance.
Often categorize concepts into hierarchies: Inheritance Hierarchies Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance in Java. RHS – SOC 2 What is inheritance (in Java)? Inheritance is a mechanism for enhancing existing classes What does that mean…? Defining.
 Sometimes a new class is a special case of the concept represented by another ◦ A SavingsAccount is-a BankAccount ◦ An Employee is-a Person  Can extend.
Inheritance CSC 171 FALL 2004 LECTURE 18. READING Read Horstmann, Chapter 11.
Java Programming Week 4: Inheritance (Chapter 10).
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Topic 4 Inheritance.
CSC 205 Java Programming II Inheritance Inheritance In the real world, objects aren’t usually one-of-a-kind. Both cars and trucks are examples of.
Chapter 10 Inheritance. Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Encapsulation ◦ Blackbox concept Data and method(s) Hidden details InterfaceEffect(s) methods called class.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
 Sometimes a new class is a special case of the concept represented by another ◦ A SavingsAccount is-a BankAccount ◦ An Employee is-a Person  Can extend.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Inheritance INHERITANCE: extend existing classes by adding or redefining methods, and adding instance fields Suppose we have a class Vehicle: public class.
Chapter 13 Inheritance. Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 3: An Introduction to Classes 1 Chapter 3 An Introduction to Classes.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 3 Implementing Classes
1 Principles of Computer Science II Prof. Nadeem Abdul Hamid CSC 121 – Spring 2006 Lecture Unit 4 - Inheritance.
Chapter Ten: Inheritance
Chapter 13 - Inheritance.
Lecture 3 John Woodward.
Data Structures and Algorithms revision
Chapter 3 – Implementing Classes
Lecture Notes – Inheritance (Ch 9-10)
Inheritance in Java.
Implementing Classes Yonglei Tao.
Computing with C# and the .NET Framework
Chapter Goals To become familiar with the process of implementing classes To be able to implement and test simple methods To understand the purpose and.
CSC 205 Java Programming II
Chapter Three - Implementing Classes
Chapter 10 – Inheritance Big Java by Cay Horstmann
د.سناء الصايغ الفصل الأول البرمجة الشيئية
Adapted from Java Concepts Companion Slides
AN INTRODUCTION TO OBJECTS AND CLASSES
Presentation transcript:

CHAPTER 11 INHERITANCE

CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package access control To understand the common superclass Object and to override its toString, equals, and clone methods

Inheritance Inheritance: extend classes by adding or redefining methods, and adding instance fields Example: Savings account = bank account with interest class SavingsAccount extends BankAccount { new methods new instance fields } All methods of BankAccount are automatically inherited Ok to call deposit, getBalance on SavingsAccount object Extended class = superclass, extending class = subclass Inheritance is different from realizing an interface oInterface is not a class oInterface supplies no instance fields or methods to inherit

An Inheritance Diagram

Adding a Subclass Method public class SavingsAccount extends BankAccount { public SavingsAccount(double rate) { interestRate = rate; } public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } private double interestRate; }

Layout of a Subclass Object

Syntax 11.1: Inheritance class SubclassName extends SuperclassName { methods instance fields } Example: public class SavingsAccount extends BankAccount { public SavingsAccount(double rate) { interestRate = rate; }

public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } private double interestRate; } Purpose: To define a new class that inherits from an existing class, and define the methods and instance fields that are added in the new class.

Inheritance Hierarchies Hierarchies of classes, subclasses, and sub- subclasses are common Example: Swing hierarchy Superclass JComponent has methods getWidth, getHeight AbstractButton class has methods to set/get button text and icon We will study a simple bank account hierarchy

A Part of the Hierarchy of Ancient Reptiles

A Part of the Hierarchy of Swing UI Components

Bank Account Hierarchy

Inheritance and Methods Override method: Supply a different implementation of a method that exists in the superclass Inherit method: Don't supply a new implementation of a method that exists in the superclass Add method: Supply a new method that doesn't exist in the superclass

Inheritance and Fields Inherit field: All fields from the superclass are automatically inherited Add field: Supply a new field that doesn't exist in the superclass Can't override fields

CheckingAccount Class First three transactions are free Charge $2 for every additional transaction Must override deposit, withdraw to increment transaction count deductFees method deducts accumulated fees, resets transaction count

Inherited Fields are Private Consider deposit method of CheckingAccount public void deposit(double amount) { transactionCount++; // now add amount to balance... } Can't just add amount to balance balance is a private field of the superclass Subclass must use public interface

Invoking a Superclass Method Can't just call deposit(amount) in deposit method of CheckingAccount That is the same as this.deposit(amount) Calls the same method (infinite recursion) Instead, invoke superclass method super.deposit(amount) Now calls deposit method of BankAccount class Complete method: public void deposit(double amount) { transactionCount++; super.deposit(amount); }

Syntax 11.2: Calling a Superclass Method super.methodName(parameters) Example: public void deposit(double amount) { transactionCount++; super.deposit(amount); } Purpose: To call a method of the superclass instead of the method of the current class

Superclass Construction public class CheckingAccount extends BankAccount { public CheckingAccount(double initialBalance) { // construct superclass super(initialBalance); // initialize transaction count transactionCount =0; }... } Pass parameters to superclass constructor Must be the first statement in subclass constructor

Syntax 11.3: Calling a Superclass Constructor ClassName(parameters) { super(parameters);... } Example: public CheckingAccount(double initialBalance) { super(initialBalance); transactionCount =0; } Purpose: To invoke a constructor of the superclass. Note that this statement must be the first statement of the subclass constructor.

Converting from Subclasses to Superclasses Ok to convert subclass reference to superclass reference SavingsAccount collegeFund = new SavingsAccount(10); BankAccount anAccount = collegeFund; Object anObject = collegeFund; Superclass references don't know the full story: anAccount.addInterest(); // ERROR Why would anyone want to know less about an object?

Variables of Different Types Refer to Same Object

Polymorphism Generic method: public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); } Works with any kind of bank account (plain, checking, savings) Subclass object reference converted to superclass reference other momsAccount.transfer(1000, harrysChecking); Note polymorphism: other.deposit(amount) calls CheckingAccount.deposit (and charges transaction fee) Why not just declare parameter as Object? Object class doesn't have deposit method

File AccountTest.java 1 /** 2 This program tests the BankAccount class and 3 their subclasses. 4 */ 5 public class AccountTest 6 { 7 public static void main(String[] args) 8 { 9 SavingsAccount momsSavings 10 = new SavingsAccount(0.5); CheckingAccount harrysChecking 13 = new CheckingAccount(100); momsSavings.deposit(10000); momsSavings.transfer(harrysChecking, 2000);

18 harrysChecking.withdraw(1500); 19 harrysChecking.withdraw(80); momsSavings.transfer(harrysChecking, 1000); 22 harrysChecking.withdraw(400); // simulate end of month 25 momsSavings.addInterest(); 26 harrysChecking.deductFees(); System.out.println("Mom's savings balance = $" 29 + momsSavings.getBalance()); System.out.println("Harry's checking balance = $" 32 + harrysChecking.getBalance()); 33 } 34 }

File BankAccount.java 1 /** 2 A bank account has a balance that can be changed by 3 deposits and withdrawals. 4 */ 5 public class BankAccount 6 { 7 /** 8 Constructs a bank account with a zero balance 9 */ 10 public BankAccount() 11 { 12 balance = 0; 13 } /** 16 Constructs a bank account with a given balance initialBalance the initial balance

18 */ 19 public BankAccount(double initialBalance) 20 { 21 balance = initialBalance; 22 } /** 25 Deposits money into the bank account. amount the amount to deposit 27 */ 28 public void deposit(double amount) 29 { 30 balance = balance + amount; 31 } /** 34 Withdraws money from the bank account. amount the amount to withdraw 36 */ 37 public void withdraw(double amount)

38 { 39 balance = balance - amount; 40 } /** 43 Gets the current balance of the bank account. the current balance 45 */ 46 public double getBalance() 47 { 48 return balance; 49 } /** 52 Transfers money from the bank account to another account other the other account amount the amount to transfer 55 */ 56 public void transfer(BankAccount other, double amount) 57 {

58 withdraw(amount); 59 other.deposit(amount); 60 } private double balance; 63 }

File CheckingAccount.java 1 /** 2 A checking account that charges transaction fees. 3 */ 4 public class CheckingAccount extends BankAccount 5 { 6 /** 7 Constructs a checking account with a given balance initialBalance the initial balance 9 */ 10 public CheckingAccount(int initialBalance) 11 { 12 // construct superclass 13 super(initialBalance); // initialize transaction count 16 transactionCount = 0; 17 }

18 19 public void deposit(double amount) 20 { 21 transactionCount++; 22 // now add amount to balance 23 super.deposit(amount); 24 } public void withdraw(double amount) 27 { 28 transactionCount++; 29 // now subtract amount from balance 30 super.withdraw(amount); 31 } /** 34 Deducts the accumulated fees and resets the 35 transaction count. 36 */ 37 public void deductFees()

38 { 39 if (transactionCount > FREE_TRANSACTIONS) 40 { 41 double fees = TRANSACTION_FEE * 42 (transactionCount - FREE_TRANSACTIONS); 43 super.withdraw(fees); 44 } 45 transactionCount = 0; 46 } private int transactionCount; private static final int FREE_TRANSACTIONS = 3; 51 private static final double TRANSACTION_FEE = 2.0; 52 }

File SavingsAccount.java 1 /** 2 An account that earns interest at a fixed rate. 3 */ 4 public class SavingsAccount extends BankAccount 5 { 6 /** 7 Constructs a bank account with a given interest rate rate the interest rate 9 */ 10 public SavingsAccount(double rate) 11 { 12 interestRate = rate; 13 } /** 16 Adds the earned interest to the account balance. 17 */

18 public void addInterest() 19 { 20 double interest = getBalance() * interestRate / 100; 21 deposit(interest); 22 } private double interestRate; 25 }

Access Control Level public private protected (accessible by subclasses and package) package access (the default, no modifier)

Recommended Access Levels Fields: Always private Exception: public static final constants Methods: public or private Classes: public or package Don't use protected Beware of accidental package access (forgetting public or private )

Object: The Cosmic Superclass All classes extend Object Most useful methods: o String toString() o boolean equals(Object otherObject) o Object clone()

The Object Class is the Superclass of Every Java Class

Overriding the toString Method Returns a string representation of the object Useful for debugging Example: Rectangle.toString returns something like java.awt.Rectangle[x=5,y=10,width=20,height=30] toString used by concatenation operator aString + anObject means aString + anObject. toString() Object.toString prints class name and object address Override toString : public class BankAccount { public String toString() { return "BankAccount[balance=" + balance + "]"; }... }

Overriding the equals Method equals tests for equal contents == tests for equal location Must cast the Object parameter to subclass public class Coin { public boolean equals(Object otherObject) { Coin other = (Coin)otherObject; return name.equals(other.name) && value == other.value; } }

Two References to Equal Objects

Two References to Same Object

Overriding the clone Method Copying object reference gives two references to same object BankAccount account2 = account1 ; Sometimes, need to make a copy of the object Use clone: BankAccount account2 = (BankAccount)account1. clone () ; Must cast return value because return type is Object Define clone method to make new object: public Object clone() { BankAccount cloned = new BankAccount(); cloned.balance = balance; return cloned; } Warning: This approach doesn't work with inheritance--see Advanced Topic 11.6