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

Similar documents
CSC 222: Object-Oriented Programming. Fall 2017

CSC 222: Object-Oriented Programming Spring 2012

CHAPTER 10 INHERITANCE

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

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

CSC 421: Algorithm Design and Analysis. Spring 2015

Inheritance (P1 2006/2007)

Encapsulation. Mason Vail Boise State University Computer Science

CSC 421: Algorithm Design and Analysis. Spring 2018

Intro to Computer Science 2. Inheritance

CSC 321: Data Structures. Fall 2018

CSC 321: Data Structures. Fall 2016

Handout 9 OO Inheritance.

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

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Inheritance and Subclasses

Introduction to Inheritance

COSC This week. Will Learn

CSC 222: Object-Oriented Programming. Fall 2015

Software Design and Analysis for Engineers

C# Programming for Developers Course Labs Contents

CSC Inheritance. Fall 2009

CS1083 Week 3: Polymorphism

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

Inheritance: Definition

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

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Arrays and Array Lists

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

CSC 222: Object-Oriented Programming. Fall 2017

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

Inheritance and Polymorphism. CS180 Fall 2007

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

Chapter Seven: Arrays and Array Lists. Chapter Goals

Object-Oriented Programming (Java)

Implementing Classes (P1 2006/2007)

Implementing Classes

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Binghamton University. CS-140 Fall Dynamic Types

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

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

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Check out Polymorphism from SVN. Object & Polymorphism

ICOM 4015: Advanced Programming

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

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

CS 215 Software Design Sample midterm solutions

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

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

Chapter Goals. T To understand the concept of regression testing. Chapter 6 Arrays and Array Lists. Arrays Array: Sequence of values of the same type

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

CS 455 Midterm Exam 1 Fall 2010 [Bono] Sept. 29, 2010

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

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

ENCAPSULATION AND POLYMORPHISM

Binghamton University. CS-140 Fall Chapter 9. Inheritance

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

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

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

Logistics. Final Exam on Friday at 3pm in CHEM 102

STUDENT LESSON A5 Designing and Using Classes

Quarter 1 Practice Exam

IT 313 Advanced Application Development

More Relationships Between Classes

CS 215 Software Design Sample Midterm Questions

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CSE 331 Final Exam 3/16/15 Sample Solution

PROGRAMMING LANGUAGE 2

Binghamton University. CS-140 Fall Subtyping!

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

CSC 222: Object-Oriented Programming. Fall 2015

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

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

CSC 222: Object-Oriented Programming. Fall 2017

What will this print?

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

EXAMINATIONS 2012 END-OF-YEAR SWEN222. Software Design. Question Topic Marks 1. Design Quality Design Patterns Design by Contract 12

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Inheritance (Part 2) Notes Chapter 6

CSE 413 Winter 2001 Midterm Exam

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

ENGR 2710U Midterm Exam UOIT SOLUTION SHEET

Designing Classes part 2

Example: Count of Points

CS 455 Midterm Exam 1 Fall 2010 [Bono] Sept. 29, 2010

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

9/2/2011. Chapter Goals

GROUP - A <10 questions x 4 points each = 40 points >

Example: Count of Points

Programming in C# Inheritance and Polymorphism

Where do objects come from? Good question!

CSC 222: Object-Oriented Programming. Fall Object-oriented design

COP 3330 Final Exam Review

CSCI-1200 Data Structures Fall 2017 Lecture 25 C++ Inheritance and Polymorphism

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

CN208 Introduction to Computer Programming

Topic 3 Encapsulation - Implementing Classes

Transcription:

CSC 222: Object-Oriented Programming Fall 2015 Inheritance & polymorphism Hunt the Wumpus, enumerated types inheritance, derived classes inheriting fields & methods, overriding fields and methods IS-A relationship, polymorphism super methods, super constructor instanceof, downcasting 1

Hunt the Wumpus for HW6, you will implement a text-based adventure game from the 1970's you will wander through a series of caves, with each cave connected to 3 others via tunnels there are dangers in the caves you can be eaten by a Wumpus you can fall into a bottomless pit you can be picked up and moved by bats you can sense dangers in adjacent caves you have a limited number of grenades you can throw when you smell a Wumpus 2

Cave class you must implement a class that models a single cave each cave has a name & number, and is connected to three other caves via tunnels by default, caves are empty & unvisited (although these can be updated) how do we represent the cave contents? we could store the contents as a string: "EMPTY", "WUMPUS", "BATS", "PIT" Cave c = new Cave("Cavern of Doom", 0, 1, 2, 3); c.setcontents("wumpus"); potential problems? there are only 4 possible values for cave contents the trouble with using a String to represent these is the lack of error checking c.setcontents("wumpas"); // perfectly legal, but??? 3

Enumerated types there is a better alternative for when there is a small, fixed number of values an enumerated type is a new type (class) whose value are explicitly enumerated public enum CaveContents { EMPTY, WUMPUS, PIT, BATS note that these values are NOT Strings they do not have quotes you specify a enumerated type value by ENUMTYPE.VALUE c.setcontents(cavecontents.wumpus); since an enumerated type has a fixed number of values, any invalid input would be caught by the compiler 4

CaveMaze the CaveMaze class reads in & stores a maze of caves provided version uses an ArrayList (but could have used an array) currently, only allows for moving between caves you must add functionality public class CaveMaze { private ArrayList<Cave> caves; private Cave currentcave; public CaveMaze(String filename) throws java.io.filenotfoundexception { Scanner infile = new Scanner(new File(filename)); int numcaves = infile.nextint(); this.caves = new ArrayList<Cave>(); for (int i = 0; i < numcaves; i++) { this.caves.add(null); for (int i = 0; i < numcaves; i++) { int num1 = infile.nextint(); int num2 = infile.nextint(); int num3 = infile.nextint(); int num4 = infile.nextint(); String name = infile.nextline().trim(); this.caves.set(num1, new Cave(name, num1, num2, num3, num4)); this.currentcave = this.caves.get(0); this.currentcave.markasvisited();... 5

CaveMaze (cont.) currently, can move between caves only see the names of caves you have already visited you must add the full functionality of the game (incl. adding & reacting to dangers, winning/losing)... public String move(int tunnel) { this.currentcave = this.caves.get(this.currentcave.getadjnumber(tunnel)); this.currentcave.markasvisited(); return "OK"; public String showlocation() { String message = "You are currently in " + this.currentcave.getcavename(); for (int i = 1; i <= 3; i++) { Cave adjcave = this.caves.get(this.currentcave.getadjnumber(i)); if (adjcave.hasbeenvisited()) { message += "\n else { message += "\n return message; (" + i + ") " + adjcave.getcavename(); (" + i + ") unknown";... 6

Interfaces & polymorphism recall that interfaces define a set of methods that a class must implement in order to be "certified" any class that implements those methods and declares itself is "certified" public class mylist<e> implements List<E> {... can use the interface name in place of a class name when declaring variables or passing values to methods List<String> words = new MyList<String>(); public int sum(list<integer> data) { int sum = 0; for (int i = 0; i < data.size(); i++) { sum += data.get(i); return sum; polymorphism refers to the fact that the same method call (e.g., size or get) can refer to different pieces of code when called on different objects enables the creation of generic libraries (e.g., Collections) 7

Inheritance a closely related mechanism for polymorphic behavior is inheritance one of the most powerful techniques of object-oriented programming allows for large-scale code reuse with inheritance, you can derive a new class from an existing one automatically inherit all of the fields and methods of the existing class only need to add fields and/or methods for new functionality example: savings account is a bank account with interest checking account is a bank account with transaction fees 8

BankAccount class here is an implementation of a basic BankAccount class stores account number and current balance uses static field to assign each account a unique number accessor methods provide access to account number and balance deposit and withdraw methods allow user to update the balance public class BankAccount { private double balance; private int accountnumber; private static int nextnumber = 1; public BankAccount() { this.balance = 0; this.accountnumber = BankAccount.nextNumber; BankAccount.nextNumber++; public int getaccountnumber() { return this.accountnumber; public double getbalance() { return this.balance; public void deposit(double amount) { this.balance += amount; public void withdraw(double amount) { if (amount >= this.balance) { this.balance -= amount; 9

Specialty bank accounts now we want to implement SavingsAccount and CheckingAccount a savings account is a bank account with an associated interest rate, interest is calculated and added to the balance periodically could copy-and-paste the code for BankAccount, then add a field for interest rate and a method for adding interest a checking account is a bank account with some number of free transactions, with a fee charged for subsequent transactions could copy-and-paste the code for BankAccount, then add a field to keep track of the number of transactions and a method for deducting fees disadvantages of the copy-and-paste approach tedious work lots of duplicate code code drift is a distinct possibility if you change the code in one place, you have to change it everywhere or else lose consistency (e.g., add customer name to the bank account info) limits polymorphism (will explain later) 10

SavingsAccount class inheritance provides a better solution can define a SavingsAccount to be a special kind of BankAccount automatically inherit common features (balance, account #, deposit, withdraw) simply add the new features specific to a savings account need to store interest rate, provide method for adding interest to the balance general form for inheritance: public class DERIVED_CLASS extends EXISTING_CLASS { ADDITIONAL_FIELDS ADDITIONAL_METHODS note: the derived class does not explicitly list fields/methods from the existing class (a.k.a. parent class) they are inherited and automatically accessible public class SavingsAccount extends BankAccount { private double interestrate; public SavingsAccount(double rate) { this.interestrate = rate; public void addinterest() { double interest = this.getbalance()*this.interestrate/100; this.deposit(interest); 11

Using inheritance BankAccount generic = new BankAccount(); // creates bank account with 0.0 balance... generic.deposit(120.0); // adds 120.0 to balance... generic.withdraw(20.0); // deducts 20.0 from balance... System.out.println(generic.getBalance()); // displays current balance: 100.0 SavingsAccount passbook = new SavingsAccount(3.5);// creates savings account, 3.5% interest... passbook.deposit(120.0); // calls inherited deposit method... passbook.withdraw(20.0); // calls inherited withdraw method... System.out.println(passbook.getBalance()); // calls inherited getbalance method... passbook.addinterest(); // calls new addinterest method... System.out.println(passbook.getBalance()); // displays 103.5 12

CheckingAccount class can also define a class that models a checking account again, inherits basic features of a bank account assume some number of free transactions after that, each transaction entails a fee must override the deposit and withdraw methods to also keep track of transactions can call the versions from the parent class using super super.parent_method(); public class CheckingAccount extends BankAccount { private int transactioncount; private static final int NUM_FREE = 3; private static final double TRANS_FEE = 2.0; public CheckingAccount() { this.transactioncount = 0; public void deposit(double amount) { super.deposit(amount); this.transactioncount++; public void withdraw(double amount) { super.withdraw(amount); this.transactioncount++; public void deductfees() { if (this.transactioncount > CheckingAccount.NUM_FREE) { double fees = CheckingAccount.TRANS_FEE * (this.transactioncount CheckingAccount.NUM_FREE); super.withdraw(fees); this.transactioncount = 0; 13

Interfaces & inheritance recall that with interfaces can have multiple classes that implement the same interface can use a variable of the interface type to refer to any object that implements it List<String> words1 = new ArrayList<String>(); List<String> words2 = new LinkedList<String>(); can use the interface type for a parameter, pass any object that implements it public void DoSomething(List<String> words) {... --------------------------------------------- DoSomething(words1); DoSomething(words2); the same capability holds with inheritance could assign a SavingsAccount object to a variable of type BankAccount could pass a CheckingAccount object to a method with a BankAccount parameter 14

IS-A relationship the IS-A relationship holds when inheriting an object of the derived class is still an object of the parent class anywhere an object of the parent class is expected, can provide a derived object consider a real-world example of inheritance: animal classification ANIMAL FISH MAMMAL BIRD CARP GOLDFISH DOG CAT HUMAN DUCK BLUEJAY 15

Polymorphism in our example a SavingsAccount is-a BankAccount (with some extra functionality) a CheckingAccount is-a BankAccount (with some extra functionality) whatever you can do to a BankAccount (e.g., deposit, withdraw), you can do with a SavingsAccount or Checking account derived classes can certainly do more (e.g., addinterest for SavingsAccount) derived classes may do things differently (e.g., deposit for CheckingAccount) polymorphism: the same method call can refer to different methods when called on different objects the compiler is smart enough to call the appropriate method for the object BankAccount acc1 = new SavingsAccount(4.0); BankAccount acc2 = new CheckingAccount(); acc1.deposit(100.0); // calls the method defined in BankAccount acc2.deposit(100.0); // calls the method defined in CheckingAccount allows for general-purpose code that works on a class hierarchy 16

import java.util.arraylist; public class AccountAdd { public static void main(string[] args) { SavingsAccount xmasfund = new SavingsAccount(2.67); xmasfund.deposit(250.0); Example use SavingsAccount carmoney = new SavingsAccount(1.8); carmoney.deposit(100.0); CheckingAccount living = new CheckingAccount(); living.deposit(400.0); living.withdraw(49.99); ArrayList<BankAccount> finances = new ArrayList<BankAccount>(); finances.add(xmasfund); finances.add(carmoney); finances.add(living); addtoall(finances, 5.0); showall(finances); note: in addtoall, the appropriate deposit method is called on each BankAccount (depending on whether it is really a SavingsAccount or CheckingAccount) private static void addtoall(arraylist<bankaccount> accounts, double amount) { for (int i = 0; i < accounts.size(); i++) { accounts.get(i).deposit(amount); private static void showall(arraylist<bankaccount> accounts) { for (int i = 0; i < accounts.size(); i++) { System.out.println(accounts.get(i).getAccountNumber() + ": $" + accounts.get(i).getbalance()); 17

In-class exercise define the BankAccount, SavingsAccount, and CheckingAccount classes create objects of each class and verify their behaviors are account numbers consecutive regardless of account type? should they be? what happens if you attempt to withdraw more than the account holds? is it ever possible to have a negative balance? 18

Another example: colored dice public class Die { private int numsides; private int numrolls; public Die(int sides) { this.numsides = sides; this.numrolls = 0; public int roll() { this.numrolls++; return (int)(math.random()*this.numsides)+1; public int getnumsides() { return this.numsides; we already have a class that models a simple (non-colored) die can extend that class by adding a color field and an accessor method need to call the constructor for the Die class to initialize the numsides and numrolls fields super(args); public enum DieColor { RED, WHITE public int getnumrolls() { return this.numrolls; public class ColoredDie extends Die { private DieColor diecolor; public ColoredDie(int sides, DieColor c){ super(sides); this.diecolor = c; public DieColor getcolor() { return this.diecolor; 19

ColoredDie example consider a game in which you roll a collection of dice and sum their values import java.util.arraylist; import java.util.collections; public class RollGame { private ArrayList<ColoredDie> dice; private static final int NUM_DICE = 5; public RollGame() { this.dice = new ArrayList<ColoredDie>(); there is one "bonus" red die that counts double this.dice.add(new ColoredDie(6, DieColor.RED)); for (int i = 1; i < RollGame.NUM_DICE; i++) { this.dice.add(new ColoredDie(6, DieColor.WHITE)); Collections.shuffle(dice); public int rollpoints() { int total = 0; for (int i = 0; i < NUM_DICE; i++) { int roll = this.dice.get(i).roll(); if (this.dice.get(i).getcolor() == DieColor.RED) { total += 2*roll; else { total += roll; return total; 20

instanceof if you need to determine the specific type of an object use the instanceof operator can then downcast from the general to the more specific type note: the roll method is defined for all Die types, so can be called regardless however, before calling getcolor you must downcast to ColoredDie import java.util.arraylist; import java.util.collections; public class RollGame { private ArrayList<Die> dice; private static final int NUM_DICE = 5; public RollGame() { this.dice = new ArrayList<Die>(); this.dice.add(new ColoredDie(6, DieColor.RED)); for (int i = 1; i < RollGame.NUM_DICE; i++) { this.dice.add(new Die(6)); Collections.shuffle(dice); public int rollpoints() { int total = 0; for (Die d : this.dice) { int roll = this.dice.get(i).roll(); total += roll; if (d instanceof ColoredDie) { ColoredDie cd = (ColoredDie)d; if (cd.getcolor() == DieColor.RED) { total += roll; return total; 21

OO summary interfaces & inheritance both provide mechanism for class hierarchies enable the grouping of multiple classes under a single name an interface only specifies the methods that must be provided each class that implements the interface must provide those methods a class can implement more than one interface a derived class can inherit fields & methods from its parent can have additional fields & methods for extended functionality can even override existing methods if more specific versions are appropriate the IS-A relationship holds using both interfaces & inheritance if class C implements interface I, an instance of C "is a(n)" instance of I if class C extends parent class P, an instance of C "is a(n)" instance of P polymorphism: obj.method() can refer to different methods when called on different objects in the hierarchy e.g., savacct.withdraw(20); chkacct.withdraw(20); 22