1 CSC 222: Computer Programming II Spring 2005 Inheritance  derived class, parent class  inheriting fields & methods, overriding fields and methods 

Slides:



Advertisements
Similar presentations
GridWorld Case Study Part 3 GridWorld Classes and Interfaces A Summary by Jim Mims.
Advertisements

Chapter 13 - Inheritance. Goals To learn about inheritance To learn about inheritance To understand how to inherit and override superclass methods To.
Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?
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.
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.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Object-Oriented Programming in C++ Lecture 6 Inheritance.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
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.
Object-Oriented Programming Part 2 Bank Account Exercise Hood College JETT Workshop Dept. of Computer Science February
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.
Chapter 2 – An Introduction to Objects and Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Part III. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Object Oriented Design CSC 171 FALL 2001 LECTURE 12.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 19 / 2007 Instructor: Michael Eckmann.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Abstract Classes and Interfaces
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
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)
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Programming Languages and Paradigms Object-Oriented Programming.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Writing Classes (Chapter 4)
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
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.
Classes CS 21a: Introduction to Computing I First Semester,
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.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Topic 4 Inheritance.
Inheritance A Review of Objects, Classes, and Subclasses.
CHAPTER 11 INHERITANCE. CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
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.
The GridWorld Case Study Program Section 1 - Overview of the Class Hierarchies Section 2 - The Actor Class Section 3 - The Rock and Flower Classes Section.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
 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.
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
Chapter 13 Inheritance. Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
© A+ Computer Science - Visit us at Full Curriculum Solutions M/C Review Question Banks.
Chapter 13 - Inheritance.
CSC 222: Object-Oriented Programming Fall 2015
CSC 222: Object-Oriented Programming Spring 2017
Lecture Notes – Inheritance (Ch 9-10)
Inheritance in Java.
CSC 222: Object-Oriented Programming Fall 2017
Phil Tayco Slide version 1.1 Created Oct 30, 2017
Computing with C# and the .NET Framework
Chapter Three - Implementing Classes
Agenda About Homework for BPJ lesson 36 About practice of last class
Adapted from Java Concepts Companion Slides
Presentation transcript:

1 CSC 222: Computer Programming II Spring 2005 Inheritance  derived class, parent class  inheriting fields & methods, overriding fields and methods  bank account example  IS-A relationship, polymorphism  super methods, super constructor

2 Inheritance inheritance is a mechanism for enhancing existing classes  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

3 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() { balance = 0; accountNumber = nextNumber; nextNumber++; } public int getAccountNumber() { return accountNumber; } public double getBalance() { return balance; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { if (amount >= balance) { balance -= amount; }

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

5 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 } public class SavingsAccount extends BankAccount { private double interestRate; public SavingsAccount(double rate) { interestRate = rate; } public void addInterest() { double interest = getBalance()*interestRate/100; deposit(interest); } } 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

6 Using inheritance BankAccount generic = new BankAccount();// creates bank account with 0.0 balance... generic.deposit(120.0);// adds to balance... generic.withdraw(20.0);// deducts 20.0 from balance... System.out.println(generic.getBalance());// displays current balance: 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

7 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() { transactionCount = 0; } public void deposit(double amount) { super.deposit(amount); transactionCount++; } public void withdraw(double amount) { super.withdraw(amount); transactionCount++; } public void deductFees() { if (transactionCount > NUM_FREE) { double fees = TRANS_FEE * (transactionCount – NUM_FREE); super.withdraw(fees); } transactionCount = 0; }

8 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 Comparable c1 = new String("foo"); Comparable c2 = new Integer(5);  can use the interface type for a parameter, pass any object that implements it public void DoSomething(Comparable c) {... } DoSomething("foo"); DoSomething(5);// note: 5 is autoboxed into an Integer 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

9 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 CARPGOLDFISH MAMMAL DOGCATHUMAN BIRD DUCKBLUEJAY

10 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

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

12 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?

13 Another example: colored dice 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 class Die { private int numSides; private int numRolls; public Die(int sides) { numSides = sides; numRolls = 0; } public int roll() { numRolls++; return (int)(Math.random()*numSides) + 1; } public int getNumSides() { return numSides; } public int getNumRolls() { return numRolls; } public class ColoredDie extends Die { private String dieColor; public ColoredDie(int sides, String color) { super(sides); dieColor = color; } public String getColor() { return dieColor; }

14 ColoredDie example consider a game in which you roll a collection of dice and sum their values  there is one "bonus" red die that counts double import java.util.ArrayList; import java.util.Collections; public class RollGame { private ArrayList dice; private static final int NUM_DICE = 5; public RollGame() { dice = new ArrayList (); dice.add(new ColoredDie(6, "red")); for (int i = 1; i < NUM_DICE; i++) { dice.add(new ColoredDie(6, "white")); } Collections.shuffle(dice); } public int rollPoints() { int total = 0; for (int i = 0; i < NUM_DICE; i++) { int roll = dice.get(i).roll(); if (dice.get(i).getColor().equals("red")) { total += 2*roll; } else { total += roll; } return total; }

15 GridWorld GridWorld is a graphical environment under development by Cay Horstmann  based on the AP Marine Biology Case Study  can place actors in a Grid and have them move around and interact

16 Downloading the GridWorld download  you can store the file anywhere, e.g., the Desktop extract all of the files start up BlueJ, select Open Project and browse to select GridWorld call the main method of the CritterDemo class  the initial grid has a Rock and a Critter  can click on the Step button to see one move of the Critter (Rocks don't move)  can click on the Run button to see repeated moves  can also click on a grid space to add a Rock or Critter

17 GridWorld base classes Grid : an interface that defines a 2-dimensional grid of objects BoundedGrid : a class that implements Grid, using a 2-D array UnboundedGrid : a class that implements Grid, using a Map (later) Location: a class that encapsulates a location (row, col) on the Grid Actor: class that defines a generic actor that can move around a Grid  public int getDirection()  public Color getColor()  public void setColor(Color newColor)  public void turn(int angle)  public Location move(Location loc, Grid gr)  public void act(Location loc, Grid gr) act method is empty for Actor  must define a class that inherits from Actor, overrides act to behave as desired

18 Rock class a rock is an actor that does nothing!  must override the move method so that the rock can't move  must override the setColor method since all rocks are black public class Rock extends Actor { // rocks don't move, so just returns current location public Location move(Location loc, Grid env) { return loc; } // rocks are always black, so disable any color change public void setColor(Color newColor) { // does nothing }

19 Critter class a Critter is an animal that scurries around the grid  if clear, it will move in its current direction  if blocked, it will turn 135 degrees to the right (backwards diagonal) public class Critter extends Actor { public Critter() { setColor(Color.GREEN); } public Critter(Color color) { setColor(color); } public void act(Location loc, Grid gr) { Location newLoc = move(loc, gr); if (loc.equals(newLoc)) { turn(135);// if didn't move, then turn }

20 Other actors can define other Actor classes that define different behaviors  Destroyer class moves similarly to Critter, but destroys any object it comes in contact with uses Grid method getAllNeighborLocations to get surrounding locations can then check each location to see if empty – if not, then remove contents can inherit from previously defined classes to modify behaviors  FastCritter class moves similarly to Critter, but moves two steps instead of one since derived from Critter, could be used anywhere a Critter is expected other actors?