340 likes | 829 Views
Chapter 5 - Object-Oriented Programming 1. Introduction. What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes.
E N D
Chapter 5 - Object-Oriented Programming 1 Introduction • 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.
Employee Clerk Manager Driver Purpose of Inheritance • Extend the functionality of an existing class. • Share the commonality between two or more classes .
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). ChequeAccount inherits BankAccount Example class BankAccount { private double balance; public double getBalance(); // other member functions } class ChequeAccount extends BankAccount { public void WriteCheque (double amount) { //... } // other member functions }
Syntax superclass subclass class YYYY extends XXXX { ...... }
Java does not support multiple inheritance. i.e. A subclass cannot inherit from more than one superclass. X class PT_Stduent extends Student, Worker { • Inheritance is between classes, NOT between objects.
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(); } }
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 } }
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 Movieextends 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 } }
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 • 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:
Why is it best to use super()? • You don't have to use super; the following would also work as a constructor for Movie : // constructor public Movie( String ttl, int lngth, String dir, String rtng ) { title = ttl; length = lngth; avail = true; director = dir; rating = rtng; } • 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; } ......
The additional information (director and rating) is NOT printed. New TapeStore Class • Here is an example program that makes use of the two classes VideoTape and Movie: 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(); } } Output: Microcosmos, 90 min. available:true Jaws, 120 min. available:true
Method Overriding • We need a new show() method in the class Movie: // added to class Movie public void show() { System.out.println(title + ", " + length + " min. available:" + avail); System.out.println( "dir: " + director + " " + rating ); } • 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:true Jaws, 120 min. available:true dir: Spielberg PG
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!!
Call the show method of superclass (VideoTape) 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 ); }
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 Movieextends 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 ); } }
VideoTape Movie MusicVideo 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.
The class MusicVideo should look like the following: 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 new TapeStore class: 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(); } } Output: Microcosmos, 90 min. available:true Jaws, 120 min. available:true dir: Spielberg PG Dancing Queen, 30 min. available:true artist: Beach Girls style: Pop
An Example on Overriding class 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 Override b.f() : 10 b.g() : 22 d.f() : 999 d.g() : 22
Write a program to calculate the employee salaries. More Examples Employee CommissionWorker HourlyWorker BonusHourlyWorker If a BonusHourlyWorker works more than 40 hours, he will receive 50% more for the extra hours.
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; } }
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(); } }
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.
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(); } }
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.