Download presentation
Presentation is loading. Please wait.
Published byMerry Haynes Modified over 9 years ago
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 can inherit variables and methods (operations) from other classes. The inheriting class can then add extra attributes and/or methods of its own. Introduction
2
2 Extend the functionality of an existing class. Share the commonality between two or more classes. Purpose of Inheritance Employee ClerkManagerDriver
3
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
4
4 Syntax class YYYY extends XXXX {...... } subclass superclass
5
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
6
6 More Examples SuperclassSubclasses StudentDiplomaStudent HDStudent ShapeCircle Rectangle Triange LoanCarLoan HomeLoan TravelLoan VehicleBus Truck
7
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(); }
8
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 }
9
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 ); }
10
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 titleinherited from VideoTape lengthinherited from VideoTape availinherited from VideoTape show()inherited from VideoTape directordefined in Movie ratingdefined in Movie
11
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; }......
12
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:true Jaws, 120 min. available:true The additional information (director and rating) is NOT printed.
13
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:true Jaws, 120 min. available:true dir: Spielberg PG
14
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!!
15
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 )
16
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 ); }
17
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
18
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:
19
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:true Jaws, 120 min. available:true dir: Spielberg PG Dancing Queen, 30 min. available:true artist: Beach Girls style: Pop
20
20 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
21
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.
22
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; } }
23
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(); }
24
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.
25
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(); }
26
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.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.