itm 352 class inheritance, hierarchies lecture #

61
ITM 352 Class inheritance, hierarchies Lecture #

Upload: julian-hutchinson

Post on 29-Dec-2015

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: ITM 352 Class inheritance, hierarchies Lecture #

ITM 352Class inheritance, hierarchies

Lecture #

Page 2: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 2

Announcements Good job on exam 1

» Exam 2 will be a little different Extra lab tomorrow (Friday) 10-12noon Be sure to get started on HW3

» Several parts!!

Page 3: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 3

Topics For Today Review of Objects Basic Inheritance UML

Page 4: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 4

An abstraction that represents both memory and functionality

» memory: resolution of a component’s static qualities such as

attributes and relationships.

» Functionality: set of methods that embody operations

Object Abstractions

Attributes

Page 5: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 5

Object Relationships Objects interact (share data, invoke operations) through

relationships

kool!

manages

ownsanEnvironment

aWeapon

aRobot

Page 6: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 6

Object QualitiesYou want to specify the following information for each object:

Identity -

Defining quality -

Name -

Attributes -

Behaviors -

Relationships -

State Groups -

Constraints -

Page 7: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 7

Classes: Summary Describe objects of the same type (type-of)

» Some qualities– behaviors (methods)– attributes (instance variables)– constraints

» Many possible quality resolutions - maintained in objects Describe how an object of a given type is created (instantiated)

in any given situation (instance)

Page 8: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 8

Classes and objects (redressed) Every class has objects, or instances, created using the new operation.

Think of the class as an object-producing machine.

new

new

Robot

String

aRobot

anotherRobot

aString

anotherString

Page 9: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 9

Java Objects Literally an instance of a Class (which shockingly is itself, an

object!)» Class defines and creates (instantiates) an object» always have a reference after instantiation

Behaviors are instance methods» methods contain operations» do not have to accept or return values

Attributes are instance variables» all variables must be typed» defined outside of any method

Page 10: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 10

Objects and Class (redressed)

Directly describing object structures is inefficient » many objects have the same qualities, just different quality

resolutions Java uses the concept of a Class to group the same “type-of”

objects together» A Class contains the description on how to create objects of

particular type. Sometimes called a “factory object” or “metaobject”

Objects are constructed (instantiated) through their Class definitions

Page 11: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 11

But there’s more…

Class Inheritanceor

Where there’s a will, there are relatives

Page 12: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 12

Chapter 7

Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Inheritance

Page 13: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 13

Principles of OOP

OOP - Object-Oriented Programming Principles discussed in previous chapters:

» Information Hiding» Encapsulation» Polymorphism

In this chapter» Inheritance

Page 14: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 14

Why OOP?

To try to deal with the complexity of programs To apply principles of abstraction to simplify the tasks

of writing, testing, maintaining and understanding complex programs

To increase code reuse» to reuse classes developed for one application in

other applications instead of writing new programs from scratch ("Why reinvent the wheel?")

Inheritance is a major technique for realizing these objectives

Page 15: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 15

Inheritance Overview

Inheritance allows you to define a very general class then later define more specialized classes by adding new detail» the general class is called the base or parent class

The specialized classes inherit all the properties of the general class» specialized classes are derived from the base class» they are called derived or child classes

After the general class is developed you only have to write the "difference" or "specialization" code for each derived class

A class hierarchy: classes can be derived from derived classes (child classes can be parent classes)» any class higher in the hierarchy is an ancestor class» any class lower in the hierarchy is a descendent class

Page 16: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 16

An Example of Inheritance:a Person Class

The base class: Display 7.1 Constructors:

» a default constructor» one that initializes the name attribute (instance variable)

Accessor methods:» setName to change the value of the name attribute» getName to read the value of the name attribute» writeOutput to display the value of the name attribute

One other class method:» sameName to compare the values of the name attributes for

objects of the class Note: the methods are public and the name attribute private

Page 17: ITM 352 Class inheritance, hierarchies Lecture #

public class Person { // Instance variable section private String name; // Constructors public Person() { // Default constructor name = "No name yet."; } public Person(String initialName) { // Constructor for just the name name = initialName; } // Set/get methods public void setName(String newName) { name = newName; } public String getName() { return name; } // Other methods public void writeOutput() { System.out.println("Name: " + name); } public boolean sameName(Person otherPerson) { return (this.name.equalsIgnoreCase(otherPerson.name)); } }

A PersonBase ClassDisplay 7.1

Chapter 6 Java: an Introduction to Computer Science & Programming - Walter Savitch 17

Page 18: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 18

Derived Classes: a Class Hierarchy

The base class can be used to implement specialized classes» For example: student, employee, faculty, and staff

Classes can be derived from the classes derived from the base class, etc., resulting in a class hierarchy

Person

Student Employee

Faculty StaffUndergraduate Graduate

MastersDegree NonDegreePhD

Page 19: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 19Chapter 6 Java: an Introduction to Computer Science & Programming - Walter Savitch 19

Example of Adding Constructor in a Derived Class: Student

Two new constructors (one on next slide)» default initializes attribute studentNumber to 0

super must be first action in a constructor definition» Included automatically by Java if it is not there» super()calls the parent default constructor

public class Student extends Person{ private int studentNumber; public Student() { super(); studentNumber = 0; }…

Keyword extends in first line» creates derived

class from base class

» this is inheritanceThe first few lines of Student class(Display 7.3):

Page 20: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 20Chapter 6 Java: an Introduction to Computer Science & Programming - Walter Savitch 20

Example of Adding Constructor in a Derived Class: Student

Passes parameter newName to constructor of parent class Uses second parameter to initialize instance variable that is not in parent class.

public class Student extends Person{. . . public Student(String newName, int newStudentNumber) { super(newName); studentNumber = newStudentNumber; }. . .

More lines of Student class(Display 7.3):

Page 21: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 21

More aboutConstructors in a Derived Class

Constructors can call other constructors Use super to invoke a constructor in parent class

» as shown on the previous slide Use this to invoke a constructor within the class

» shown on the next slide Whichever is used must be the first action taken by the

constructor Only one of them can be first, so if you want to invoke both:

» Use a call with this to call a constructor with super

Page 22: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 22

Example of a constructor using this

Student class has a constructor with two parameters: String for the name attribute and int for the studentNumber attribute

public Student(String newName, int newStudentNumber) { super(newName); studentNumber = newStudentNumber; }

Another constructor within Student takes just a String argument and initializes the studentNumber attribute to a value of 0:» calls the constructor with two arguments, initialName (String) and 0

(int), within the same class

public Student(String initialName){ this(initialName, 0);}

Page 23: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 23Chapter 6 Java: an Introduction to Computer Science & Programming - Walter Savitch 23

Example of Adding an Attribute in a Derived Class: Student

Note that an attribute for the student number has been added» Student has this attribute in addition to name,

which is inherited from Person

A line from the Student class:

private int studentNumber;

Page 24: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 24

Example of Overriding a Method in a Derived Class: Student Both parent and derived classes have a writeOutput method Both methods have the same parameters (none)

» they have the same signature The method from the derived class overrides (replaces) the

parent's It will not override the parent if the parameters are different (since

they would have different signatures) This is overriding, not overloading

public void writeOutput(){ System.out.println("Name: " + getName()); System.out.println("Student Number : " studentNumber);}

Page 25: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 25

Call to an Overridden Method

Use super to call a method in the parent class that was overridden (redefined) in the derived class

Example: Student redefined the method writeOutput of its parent class, Person

Could use super.writeOutput() to invoke the overridden (parent) method

public void writeOutput(){ super.writeOutput(); System.out.println("Student Number : " studentNumber);}

Page 26: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 26

Overriding Verses Overloading

Overriding

Same method name

Same signature One method in

ancestor, one in descendant

Overloading

Same method name

Different signature Both methods can be

in same class

Page 27: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 27

The final Modifier

Specifies that a method definition cannot be overridden with a new definition in a derived class

Example:

public final void specialMethod()

{

. . . Used in specification of some methods in standard libraries Allows the compiler to generate more efficient code Can also declare an entire class to be final, which means it

cannot be used as a base class to derive another class

Page 28: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 28

private & publicInstance Variables and Methods

private instance variables from the parent class are not available by name in derived classes» "Information Hiding" says they should not be » use accessor methods to change them, e.g. reset for a Student object to change the name attribute

private methods are not inherited!» use public to allow methods to be inherited» only helper methods should be declared private

Page 29: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 29

What is the "Type" of a Derived class?

Derived classes have more than one type Of course they have the type of the derived class (the class they

define) They also have the type of every ancestor class

» all the way to the top of the class hierarchy All classes derive from the original, predefined class Object Object is called the Eve class since it is the original class for

all other classes

Page 30: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 30

Assignment Compatibility

Can assign an object of a derived class to a variable of any ancestor type

Person josephine;

Employee boss = new Employee();

josephine = boss;

Can not assign an object of an ancestor class to a variable of a derived class type

Person josephine = new Person();

Employee boss;

boss = josephine; Not allowed

OK

Person

Employee

Person is the parent class of Employee in this example.

Page 31: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 31

Character Graphics Example

Figure

Box Triangle

Instance variables:offsetMethods:setOffset getOffsetdrawAt drawHere

Instance variables:offset height widthMethods:setOffset getOffsetdrawAt drawHerereset drawHorizontalLinedrawSides drawOneLineOfSidesspaces

Instance variables:offset baseMethods:setOffset getOffsetdrawAt drawHerereset drawBasedrawTop spaces

InheritedOverridesStatic

Page 32: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 32

How do Programs KnowWhere to Go Next?

Programs normally execute in sequence Non-sequential execution occurs with:

» selection (if/if-else/switch) and repetition (while/do-while/for)(depending on the test it may not go in sequence)

» method calls, which jump to the location in memory that contains the method's instructions and returns to the calling program when the method is finished executing

One job of the compiler is to try to figure out the memory addresses for these jumps

The compiler cannot always know the address» sometimes it needs to be determined at run time

Page 33: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 33

Static and Dynamic Binding

Binding: determining the memory addresses for jumps Static: done at compile time

» also called offline Dynamic: done at run time Compilation is done offline

» it is a separate operation done before running a program

Binding done at compile time is, therefor, static, and Binding done at run time is dynamic

» also called late binding

Page 34: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 34

Example of Dynamic Binding: General Description

Derived classes call a method in their parent class which calls a method that is overridden (defined) in each of the derived classes» the parent class is compiled separately and before

the derived classes are even written» the compiler cannot possibly know which address

to use» therefore the address must be determined (bound)

at run time

Page 35: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 35

Dynamic Binding: Specific Example

Parent class: Figure» Defines methods: drawAt and drawHere» drawAt calls drawHere

Derived class: Box extends Figure» Inherits drawAt » redefines (overrides) drawHere» Calls drawAt

– uses the parent's drawAt method– which must call this, the derived class's, drawHere

method Figure is compiled before Box is even written, so the address

of drawHere(in the derived class Box) cannot be known then» it must be determined during run time, i.e. dynamically

Page 36: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 36

Polymorphism

Using the process of dynamic binding to allow different objects to use different method actions for the same method name

Originally overloading was considered to be polymorphism

Now the term usually refers to use of dynamic binding

Page 37: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 37

Summary

A derived inherits the instance variables & methods of the base class

A derived class can create additional instance variables and methods

The first thing a constructor in a derived class normally does is call a constructor in the base class

If a derived class redefines a method defined in the base class, the version in the derived class overrides that in the base class

Private instance variables and methods of a base class cannot be accessed directly in the derived class

If A is a derived class of class B, than A is both a member of both classes, A and B » the type of A is both A and B

Page 38: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 38

UML

Universal Modeling Language Used to facilitate OOAD A “standard” choice in many development efforts UML is one approach commonly incorporated into object

oriented modeling software, such as Rational Rose

Page 39: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 39

UML in ITM 352 (and 353)

We will use only very basic UML» Use-case diagrams» Object relationship diagrams» Basic class (object types) diagrams

– association, part-of, kind-of

Page 40: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 40

Example Use-case

add new robot starts contest

submits robot to contest gets contest results

1007 Student

Contest Admin.

1007 Instructor

The Robot Warz System

The Robot Warz Actors

monitors contestuses

Page 41: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 41

Example Use-case

starts contest

Contest Admin.

Contest Admin. Interface

set up contest environment

run contest

ContestDisplay

Behavior

Page 42: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 42

:RobotPart

:Robot :EnvironmentmyEnvironment

:Weapon

:Radar

:Engine

robotParts

:PlayPen

Example Class diagram

reference

sourceobject

relationship

destinationobject

part-ofrelationship

sub-classrelationship

Page 43: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 43

More Examples of Inheritance

Page 44: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 44

Bank Accounts Consider these three classes:

BankAccount

SavingsAccount

CheckingAccount

holds money

earns interest on money held

writes checks on money held

Page 45: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 45

public class BankAccount {

private double balance;

public BankAccount()

{ balance = 0; }

public BankAccount(double initialBalance)

{ balance = initialBalance; }

public void deposit(double amount)

{ balance = balance + amount; }

public void withdraw(double amount)

{ balance = balance - amount; }

public double getBalance()

{ return balance; }

public void transfer(BankAccount other, double amount)

{ withdraw(amount);

other.deposit(amount);

}

}

Page 46: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 46

Sub-types SavingsAccount and CheckingAccount

» Use all the behaviors of a BankAccount» Use all the attributes of a BankAccount» Add some new behaviors and attributes

This is because they are both types-of BankAccount » They are a “kind-of” BankAccount » A specialization or sub-type» We are intentionally making a distinction

To implement we could » Create two new classes and simply copy all the instance methods

and instance variables from BankAccount and add the new stuff» Add new behaviors and attributes to BankAccount and use

conditionals to determine when savings vs. checking

Page 47: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 47

Inheritance Both implementation approaches are somewhat in-elegant Java supports a more elegant approach, inheritance

» Use the extends keyword in the class definition

Page 48: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 48

Inheritance (cont.)

public class SavingsAccount extends BankAccount

private double interestRate;

{ public SavingsAccount(double rate)

{ interestRate = rate;

}

public void addInterest()

{ double interest = getBalance() * interestRate / 100;

deposit(interest);

}

}

Page 49: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 49

Terminology BankAccount is called the superclass or base class. SavingsAccount and CheckingAccount are subclasses or

derived classes.

We say SavingsAccount and CheckingAccount inherit from BankAccount , because they obtain the definitions of getBalance and deposit, etc.SavingsAccount

BankAccount

CheckingAccount

Page 50: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 50

What this meansSavingsAccount has five operations:deposit, withdraw, getBalance, transfer, addInterest

It is as if SavingsAccount were defined as

public class SavingsAccount {

private double balance;

private double interestRate;

public SavingsAccount(){ … }

public SavingsAccount(double initialBalance) { … }

public void deposit(double amount) { … }

public void withdraw(double amount) { … }

public double getBalance() { … }

public void transfer(BankAccount other, double amount) {…}

}

Page 51: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 51

What this means (cont.)

Similarly for CheckingAccount.

Variables can be declared of type BankAccount. SavingsAccount and CheckingAccount objects can be assigned to them.

BankAccount mySavingsAccount = new SavingsAccount(), myCheckingAccount = new CheckingAccount ();

Page 52: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 52

Casting and Converting

Both can use any methods and ivars from BankAccount

mySavingsAccount.deposit(100);myCheckingAccount.withdrawal(1000);

myCheckingAccount.transfer(mySavingsAccount, 100);

But notmySavingsAccount.addInterest();

You can re-cast if neededSavingsAccount aSavingsAccount

= (SavingsAccount) mySavingsAccount aSavingsAccount.addInterest();

Page 53: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 53

new conditional operator

Because you may declare a reference to one of its super classes (including Object), you may need to test if a reference is the type you desire. Java uses the instanceof operator for this purpose

if(myAccount instanceof SavingsAccount) myAccount.addInterest();

Page 54: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 54

Object Class Actually there is implicitly more inheritance

Everything is a Kind-of Object in Java» Any class that does not specify an extension extends Object

SavingsAccount

BankAccount

CheckingAccount

Object

Page 55: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 55

:RobotPart

:Robot :EnvironmentmyEnvironment

:Weapon

:Radar

:Engine

robotParts

:PlayPen

UML Inheritance Notation

sub-class

super-class

sub-classrelationship

Page 56: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 56

A Small Problem… Sometimes you will need to initialize a subclasses instance variables (in

a constructor) but not know (or care) how the superclass initializes the inherited ones.

Java provides a simple solution to this using the super operation.

Page 57: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 57

super public class SavingsAccount extends BankAccount

private double interestRate;

{ public SavingsAccount(double rate, double startingBal)

{ super(startingBal);

interestRate = rate;

}

public void addInterest()

{ double interest = getBalance() * interestRate / 100;

deposit(interest);

}

}

Page 58: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 58

Method redefinition in subclasses

A very important aspect of inheritance is that instance methods can be redefined instead of being inherited. Sometimes this is called overriding

You do this by simply using the exact same method name (including parameters and return type)

Real rule is: if B is a subclass of A then it inherits instance variables of A and instance methods of A, except those that it defines itself.

» Instance variables are not overridden – if B re-defines ivars then there would be two independent (local to each class) versions

Why would you do this?

» To modify the behavior of the superclass

» In general you try to limit overriding (elegance again)

Page 59: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 59

Overriding: Checking Account

A CheckingAccount may want to modify the behavior of the deposit, withdrawal, and transfer methods of BankAccount in order to keep track of the number of transactions (to asses a use fee).

The super keyword can be used to call a method of the superclass if the modifications are additions only.

Page 60: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 60

public class CheckingAccount extends BankAccount

{ public CheckingAccount(double initialBalance)

{ // construct superclass

super(initialBalance);

// initialize transaction count

transactionCount = 0;

}

public void deposit(double amount)

{ transactionCount++;

// now add amount to balance

super.deposit(amount);

}

public void withdraw(double amount)

{ transactionCount++;

// now subtract amount from balance

super.withdraw(amount);

}

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;

}

Page 61: ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 61

Inheritance in the Java API

Inheritance is used extensively in the Java API» The Applet class has definitions of init, paint, repaint,

etc. When you define an applet, you inherit those definitions and redefine the ones you choose to.

» Applet itself inherits from its superclass, Panel, which in turn inherits from Container, which inherits from Component.