CHAPTER 10 INHERITANCE

Similar documents
Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

Inheritance (P1 2006/2007)

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy

Chapter 10 Inheritance. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Intro to Computer Science 2. Inheritance

3/7/2012. Chapter Ten: Inheritance. Chapter Goals

CS1083 Week 3: Polymorphism

COSC This week. Will Learn

Handout 9 OO Inheritance.

CSC Inheritance. Fall 2009

Agenda: Notes on Chapter 3. Create a class with constructors and methods.

Implementing Classes

Implementing Classes (P1 2006/2007)

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Inheritance: Definition

Inheritance and Subclasses

CSC 222: Object-Oriented Programming. Fall Inheritance & polymorphism

Introduction to Inheritance

STUDENT LESSON A5 Designing and Using Classes

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

CSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

BankAccount account1 = new BankAccount(...);,this

ICOM 4015: Advanced Programming

Lesson 35..Inheritance

Inheritance. A mechanism for specialization A mechanism for reuse. Fundamental to supporting polymorphism

public class Account { private int id; private static int nextaccountid = 0; private String name; private double balance;

Encapsulation. Mason Vail Boise State University Computer Science

Java Puzzle Ball Nick Ristuccia

2/9/2012. Chapter Three: Implementing Classes. Chapter Goals

9/2/2011. Chapter Goals

C# Programming for Developers Course Labs Contents

Outline CSE 142. Specification vs Implementation - Review. CSE142 Wi03 F-1. Instance Variables

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

2. (True/False) All methods in an interface must be declared public.

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

The Scanner class reads data entered by the user. Methods: COSC Dr. Ramon Lawrence. Page 3. COSC Dr. Ramon Lawrence A) A = 6, B = 3

Class 09 Slides: Polymorphism Preconditions. Table of Contents. Postconditions

Inheritance in Ruby. You are familiar with the idea of inheritance and how to use this in programming.

Programming a Bank Database. We ll store the information in two tables: INTEGER DECIMAL(10, 2)

Object-Oriented Programming

Check out Polymorphism from SVN. Object & Polymorphism

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

CSCI-1200 Data Structures Spring 2016 Lecture 23 C++ Exceptions, Inheritance, and Polymorphism

Object-oriented basics. Object Class vs object Inheritance Overloading Interface

CS 215 Software Design Sample Midterm Questions

Principles of Software Construction: Objects, Design, and Concurrency

Objects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017

BloomBank Financial Software Design

Quarter 1 Practice Exam

Principles of Software Construction: Objects, Design and Concurrency. Packages and Polymorphism. toad Fall 2012

Principles of Software Construction: Objects, Design, and Concurrency. Part 1: Designing Classes. Design for Reuse School of Computer Science

SWC test question #01. Using objects part I

Appendix E: Using UML in Class Design

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

CN208 Introduction to Computer Programming

C++ Important Questions with Answers

OO design. Classes, Responsibilities, Collaborations (CRC) 13/9/1999 COSC

Implementing AddChoice()

Arrays Classes & Methods, Inheritance

CSE 143. "Class Relationships" Class Relationships and Inheritance. A Different Relationship. Has-a vs. Is-a. Hierarchies of Organization

Inheritance and delega9on

Inheritance. Inheritance

CS 106X, Lecture 14 Classes and Pointers

Practical Session 2 Correction Don't forget to put the InputValue.java file in each project

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program.

6.096 Introduction to C++

Eduardo M. Breijo Baullosa May 2, Assignment 17. Report

CSC 421: Algorithm Design and Analysis. Spring 2015

Review. these are the instance variables. these are parameters to the methods

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Handout 8 Classes and Objects Continued: Static Variables and Constants.

Date: AIM. Write a Java program to demo simple inheritance PROCEDURE

CSE115 Introduction to Computer Science I Coding Exercise #7 Retrospective Fall 2017

Sample Solution Assignment 5. Question R3.1

Object-Oriented Concepts

Chapter 5 Object-Oriented Programming

Instructions. Quiz #2. Name: Solutions Student Number: Signature:

1. BlueJ bank example with subclasses of BankAccount 2. Transparency of UML diagram for BankAccount class hierarchy

CSC 421: Algorithm Design and Analysis. Spring 2018

Introduction to Objects. James Brucker

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

SOFTWARE DEVELOPMENT 1. Objects III 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Inheritance and Polymorphism

$ % $ % BankAccount. public class BankAccount {... private??? balance; } "commands, transformers, mutators! "abstract state! "queries, accessors!

Where do we stand on inheritance?

CS 215 Software Design Sample midterm solutions

Chapter 9. Designing Classes. Chapter Goals. Chapter Goals. Choosing Classes. Choosing Classes. Self Test

ECE 122. Engineering Problem Solving with Java

Arrays and Array Lists

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques

Chapter 8. Arrays and Array Lists. Chapter Goals. Chapter Goals. Arrays. Arrays. Arrays

Programming Abstractions

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

6.096 Introduction to C++

Designing Classes Advanced Programming ICOM 4015 Lecture 8 Reading: Java Concepts Chapter 8

Software Design and Analysis for Engineers

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Inheritance. Transitivity

Binghamton University. CS-140 Fall Chapter 9. Inheritance

Transcription:

CHAPTER 10 INHERITANCE

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 2

An Inheritance Diagram 3

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

Layout of a Subclass Object 5

Syntax 10.1: Inheritance class SubclassName extends SuperclassName methods instance fields 6

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. 7

Inheritance Hierarchies Hierarchies of classes, subclasses, and sub-subclasses are common Real world example: Ancient reptiles We will study a simple bank account hierarchy 8

A Part of the Hierarchy of Ancient Reptiles 9

Bank Account Hierarchy 10

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 11

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 (rather the subclass field shadows the superclass field) 12

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

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 The field balance is a private field of the superclass Subclass must use public interface 14

Invoking a Superclass Method Can't just call deposit(amount) in deposit method of CheckingAccount 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); 15

Syntax 10.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 them current class 16

Superclass Construction public class CheckingAccount extends BankAccount public CheckingAccount(double initialbalance) // construct superclass super(initialbalance); // initialize transaction count transactioncount = 0;... 17

Syntax 10.3: Calling a Superclass ClassName(parameters) super(parameters);... Constructor Example: public CheckingAccount(double initialbalance) super(initialbalance); transactioncount = 0; Purpose: To invoke a constructor of the superclass. Note that this statement must be 18 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? 19

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) Note polymorphism: other.deposit(amount) calls CheckingAccount.deposit (and charges transaction fee) if other refers to a checking account Why not just declare parameter as Object? The Object class doesn't have deposit method 20

File AccountTest.java public class AccountTest public static void main(string[] args) SavingsAccount momssavings = new SavingsAccount(0.5); CheckingAccount harryschecking = new CheckingAccount(100); momssavings.deposit(10000); momssavings.transfer(2000, harryschecking); harryschecking.withdraw(1500); harryschecking.withdraw(80); momssavings.transfer(1000, harryschecking); harryschecking.withdraw(400); // simulate end of month momssavings.addinterest(); harryschecking.deductfees(); System.out.println("Mom's savings balance = $" + momssavings.getbalance()); System.out.println("Harry's checking balance = $" + harryschecking.getbalance()); 21

File BankAccount.java public class BankAccount public BankAccount() balance = 0; public BankAccount(double initialbalance) balance = initialbalance; public void deposit(double amount) balance = balance + amount; 22

public void withdraw(double amount) balance = balance - amount; public double getbalance() return balance; public void transfer(double amount, BankAccount other) withdraw(amount); other.deposit(amount); private double balance; 23

File CheckingAccount.java public class CheckingAccount extends BankAccount public CheckingAccount(int initialbalance) super(initialbalance); transactioncount = 0; public void deposit(double amount) transactioncount++; super.deposit(amount); public void withdraw(double amount) transactioncount++; super.withdraw(amount); 24

public void deductfees() if (transactioncount > FREE_TRANSACTIONS) double fees = TRANSACTION_FEE * (transactioncount - FREE_TRANSACTIONS); super.withdraw(fees); transactioncount = 0; private int transactioncount; private static final int FREE_TRANSACTIONS = 3; private static final double TRANSACTION_FEE = 2.0; 25

File SavingsAccount.java public class SavingsAccount extends BankAccount public SavingsAccount(double rate) interestrate = rate; public void addinterest() double interest = getbalance()*interestrate/100; deposit(interest); private double interestrate; 26