1 chapter 5 - object-oriented programming 1 what is inheritance? object-oriented systems allow...

26
1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes can inherit variables and methods (operations) from other classes. The inheriting class can then add extra attributes and/or methods of its own. Introduction

Upload: merry-haynes

Post on 05-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

1

Chapter 5 - Object-Oriented Programming 1

What is inheritance?• Object-oriented systems allow classes to be

defined in terms of other classes.• Classes can inherit variables and methods

(operations) from other classes. The inheriting class can then add extra attributes and/or methods of its own.

Introduction

Page 2: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

2

• Extend the functionality of an existing class.• Share the commonality between two or more

classes .

Purpose of Inheritance

Employee

Clerk Manager Driver

Page 3: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

3

Example

• In the above example, ChequeAccount inherits from BankAccount. We can say that ChequeAccount is a subclass (or derived class or child class)of BankAccount and BankAccount is called a superclass (or base class or parent class).

class BankAccount { private double balance; public double getBalance(); // other member functions}

class ChequeAccount extends BankAccount { public void WriteCheque (double amount) { //... } // other member functions}

ChequeAccount inherits BankAccount

Page 4: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

4

Syntax

class YYYY extends XXXX { ......

}

subclass superclass

Page 5: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

5

• Java does not support multiple inheritance. i.e. A subclass cannot inherit from more than one superclass.

class PT_Stduent extends Student, Worker {

• Inheritance is between classes, NOT between objects.

X

Page 6: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

6

 

 

More Examples

Superclass Subclasses

Student DiplomaStudent

HDStudent

Shape Circle

Rectangle

Triange

Loan CarLoan

HomeLoan

TravelLoan

Vehicle Bus

Truck

Page 7: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

7

Example• Here is a program that uses a class VideoTape to represent tapes

available at a video tape rental store. Inheritance is not used in this program (so far).

class VideoTape { String title; // name of the item int length; // number of minutes boolean avail; // is the tape in the store?

public VideoTape( String ttl, int lngth ) { title = ttl; length = lngth; avail = true; }

public void show() { System.out.println( title + ", " + length + " min. available:" + avail ); }}

class TapeStore { public static void main ( String args[] ) { VideoTape item1 = new VideoTape("Jaws", 120 ); item1.show(); }}

Page 8: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

8

• The output is: Jaws, 120 min. available: true

• The VideoTape class has basic information in it, and would be OK for documentaries and instructional tapes.

• But movies need more information. Let us make a class that is similar to VideoTape, but has the name of the director and a rating.

class Movie extends VideoTape { String director; // name of the director String rating; // G, PG, R, or X

// constructor public Movie( String ttl, int lngth, String dir, String rtng ) { super(ttl, lngth); // use the super class' constructor director = dir; rating = rtng; // initialize what's new to Movie }

}

Page 9: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

9

class Movie extends VideoTape { String director; // name of the director String rating; // G, PG, R, or X

// constructor public Movie( String ttl, int lngth, String dir, String rtng ) { super(ttl, lngth); // use the super class' constructor director = dir; rating = rtng; // initialize what's new to Movie }

}

class VideoTape { String title; // name of the item int length; // number of minutes boolean avail; // is the tape in the store?

public VideoTape( String ttl, int lngth ) { title = ttl; length = lngth; avail = true; }

public void show() { System.out.println( title + ", " + length + " min. available:" + avail ); }}

Page 10: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

10

• The statement super(ttl, lngth) calls the super class' constructor to initialize some of the data.

• The super() call must be the first statement in a constructor.

• The class Movie is a subclass of VideoTape. An object of type Movie has the following members in it:

member

title inherited from VideoTape

length inherited from VideoTape

avail inherited from VideoTape

show() inherited from VideoTape

director defined in Movie

rating defined in Movie

Page 11: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

11

Why is it best to use super()?

// constructor public Movie( String ttl, int lngth, String dir, String rtng ) { title = ttl; length = lngth; avail = true; director = dir; rating = rtng; }

• You don't have to use super; the following would also work as a constructor for Movie :

• You should not write the same code more than once. You might make a mistake the second time (for example: forgetting to initialize the member avail.)

class VideoTape { String title; // name of the item int length; // number of minutes boolean avail; // is the tape in the store?

public VideoTape( String ttl, int lngth ) { title = ttl; length = lngth; avail = true; } ......

Page 12: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

12

New TapeStore Class

class TapeStore2 { public static void main ( String args[] ) { VideoTape item1 = new VideoTape("Microcosmos", 90 ); Movie item2 = new Movie("Jaws", 120, "Spielberg", "PG" ); item1.show(); item2.show(); }}

• Here is an example program that makes use of the two classes VideoTape and Movie:

Output:

Microcosmos, 90 min. available:trueJaws, 120 min. available:true

The additional information (director and rating) is NOT printed.

Page 13: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

13

Method Overriding

// added to class Movie public void show() { System.out.println(title + ", " + length + " min. available:" + avail); System.out.println( "dir: " + director + " " + rating ); }

• We need a new show() method in the class Movie:

• Even though the parent has a show() method the new definition of show() in the child class will override the parent's version.

• A child overrides a method from its parent by defining a replacement method with the same signature.

Output:

Microcosmos, 90 min. available:trueJaws, 120 min. available:truedir: Spielberg PG

Page 14: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

14

Using super in a Child's Method

• Sometimes (as in the example) you want a child class to have its own method, but that method includes everything the parent's method does. Consider VideoTape's show() method:

public void show() { System.out.println( title + ", " + length + " min. available:" + avail );}

• Here is Movie's method:

public void show() { System.out.println( title + ", " + length + " min. available:" + avail ); System.out.println( "dir: " + director + " " + rating ); }

• We wrote the same code twice!!

Page 15: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

15

Using super in a Child's Method

• Can we use the show() method in the super class?

• Yes!

• You can use the super reference in this situation. • Movie's method would better be written using super:

public void show() { super.show(); System.out.println( "dir: " + director + " " + rating ); }

Call the show method of superclass (VideoTape)

Page 16: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

16

class Movie extends VideoTape { String director; // name of the director String rating; // G, PG, R, or X

// constructor public Movie( String ttl, int lngth, String dir, String rtng ) { super(ttl, lngth); // use the super class' constructor director = dir; rating = rtng; // initialize what's new to Movie } public void show() { super.show(); System.out.println( "dir: " + director + " " + rating ); }}

class VideoTape { String title; // name of the item int length; // number of minutes boolean avail; // is the tape in the store?

public VideoTape( String ttl, int lngth ) { title = ttl; length = lngth; avail = true; }

public void show() { System.out.println( title + ", " + length + " min. available:" + avail ); }}

Page 17: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

17

More Examples

• Create a new class, MusicVideo that will be like VideoTape but will have two new instance variables: artist (the name of the performer) and category ("R&B", "Pop", "Classical", "Other" ). Both of these will be Strings.

• The MusicVideo class will need its own constructor and its own show() method.

VideoTape

MusicVideoMovie

Page 18: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

18

class MusicVideo extends VideoTape { String artist; String category; // constructor public MusicVideo ( String ttl, int len, String art, String cat ) { super( ttl, len ); artist = art; category = cat; } public void show() { super.show(); System.out.println( "artist:" + artist + " style: " + category ); }}

• The class MusicVideo should look like the following:

Page 19: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

19

class TapeStore4 { public static void main ( String args[] ) { VideoTape item1 = new VideoTape("Microcosmos", 90 ); Movie item2 = new Movie("Jaws", 120, "Spielberg", "PG" ); MusicVideo item3 = new MusicVideo("Dancing Queen", 30, "Beach Girls", "Pop" ); item1.show(); item2.show(); item3.show(); }}

• The new TapeStore class:

Output:

Microcosmos, 90 min. available:trueJaws, 120 min. available:truedir: Spielberg PGDancing Queen, 30 min. available:trueartist: Beach Girls style: Pop

Page 20: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

20

An Example on Overridingclass Base { public int f() { return 10; } public int g() { return 22; }}

class Derived extends Base { public int f() { return 999; }}

public class Override { public static void main(String[] args) { Base b = new Base(); Derived d = new Derived();

System.out.println("b.f() : " + b.f()); System.out.println("b.g() : " + b.g()); System.out.println("d.f() : " + d.f()); System.out.println("d.g() : " + d.g()); }}

Output:

> java Overrideb.f() : 10b.g() : 22d.f() : 999d.g() : 22

Page 21: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

21

More Examples

• Write a program to calculate the employee salaries.

Employee

HourlyWorkerCommissionWorker

BonusHourlyWorker

If a BonusHourlyWorker works more than 40 hours, he will receive 50% more for the extra hours.

Page 22: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

22

class Employee { private String firstName; private String lastName;

public Employee( String first, String last ) { firstName = first; lastName = last; }

public String getFirstName() { return firstName; }

public String getLastName() { return lastName; }

public String toString() { return firstName+' '+lastName; }

double earnings() { return 0; }}

Page 23: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

23

class CommissionWorker extends Employee { private double salary; // base salary per week private double commission; // amount per item sold private int quantity; // total items sold for week

public CommissionWorker( String first, String last, double s, double c, int q) { super( first, last ); // call base-class constructor setSalary( s ); setCommission( c ); setQuantity( q ); }

public void setSalary( double s ) { salary = ( s > 0 ? s : 0 ); }

public void setCommission(double c) {commission = ( c>0 ? c : 0 );}

public void setQuantity( int q ) { quantity = ( q > 0 ? q : 0 ); }

public double earnings() { return salary + commission * quantity; }

public String toString(){ return "Commission worker: "+super.toString(); }}

Page 24: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

24

class HourlyWorker extends Employee { protected double wage; // wage per hour protected double hours; // hours worked for week

public HourlyWorker( String first, String last, double w, double h ) { super( first, last ); // call base-class constructor setWage( w ); setHours( h ); }

public void setWage( double w ) { wage = ( w > 0 ? w : 0 ); }

public void setHours( double h ) { hours = ( h >= 0 && h < 168 ? h : 0 ); }

public double earnings() { return wage * hours; }

public String toString() { return "Hourly worker: " + super.toString(); }}

protected members : Subclass can use it. Details in next chapter.

Page 25: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

25

class BonusHourlyWorker extends HourlyWorker { public BonusHourlyWorker( String first, String last, double w, double h ) { super( first, last, w, h); // call base-class constructor }

public double earnings() { return super.earnings() + (hours>40 ? wage*(hours-40)*0.5 : 0);

}

public String toString() { return "Bonus Hourly worker: " + super.toString(); }}

Page 26: 1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes

26

class TestEmployee { public static void main(String[] args) {

Employee emp1 = new CommissionWorker( "Sue", "Jones", 400.0, 3.0, 150); Employee emp2 = new HourlyWorker( "Karen", "Price", 13.75, 40 ); Employee emp3 = new HourlyWorker( "Peter", "Bush", 200, 45 ); Employee emp4 = new BonusHourlyWorker( "Maggie", "Jackson", 200, 45 );

System.out.println(emp1 + " earned $" + emp1.earnings() ); System.out.println(emp2 + " earned $" + emp2.earnings() ); System.out.println(emp3 + " earned $" + emp3.earnings() ); System.out.println(emp4 + " earned $" + emp4.earnings() ); }}

An Employee reference can point to its subclass objects. Details in next chapter.