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

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Chapter 1 Inheritance University Of Ha’il.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Programming With Java ICS 201 University Of Ha’il1 Chapter 8 Abstract Class.
Class Hierarchies. Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Object-Oriented Programming: Inheritance Deitel &Deitel Java SE 8.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
1. 2 Introduction to Inheritance  Access Modifiers  Methods in Subclasses  Method Overriding  Converting Class Types  Why up-cast?  Why down-cast?
Object Orientated Concepts. Overview  The world is objects  Defining an object  Not a function, it’s a method  Lets inherit want we can  Objects.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Abstract Classes. Lecture Objectives To learn about abstract classes To understand how to inherit abstract classes To understand how to override abstract.
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
Lecture 10: Inheritance Subclasses and superclasses The inheritance chain Access control The Object cosmic superclass The super keyword Overriding methods.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Abstract Classes and Interfaces
1 Introduction to Inheritance Overview l Inheritance ensures Reusability l Example of Inheritance l What is actually Inherited? l Overloading Vs. Overriding.
Chapter 10: Inheritance 1. Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
Interfaces Need arising from software engineering –Disparate groups of programmers need to agree to a “contract” that spells out how their software interacts.
Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class.
Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types.
What is inheritance? It is the ability to create a new class from an existing class.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
CSC 142 Computer Science II Zhen Jiang West Chester University
Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.
Encapsulation, Inheritance & Polymorphism. OOP Properties Encapsulation ­The process of creating programs so that information within a class is not accessible.
Some Object-Oriented Programming (OOP) Review. Let’s practice writing some classes Write an Employee class with methods that return values for the following.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Peyman Dodangeh Sharif University of Technology Fall 2014.
MIT AITI 2004 – Lecture 12 Inheritance. What is Inheritance?  In the real world: We inherit traits from our mother and father. We also inherit traits.
Inheritance  Inheritance is a fundamental object-oriented technique  it enhances software design and promotes reuse  We will focus on:  deriving new.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
O O P Polymorphism Object Oriented Programming Prepared & Presented by: dr.Ismail Farahat Chapter 4.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Advanced Programming Inheritance (2). 2 Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Inheritance ndex.html ndex.htmland “Java.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CMSC 202 Polymorphism 2 nd Lecture. Aug 6, Topics Constructors and polymorphism The clone method Abstract methods Abstract classes.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Lecture 12 Inheritance.
Inheritance and Polymorphism
Polymorphism 2nd Lecture
Phil Tayco Slide version 1.1 Created Oct 30, 2017
Chapter 5 Hierarchies IS-A associations superclasses subclasses
Lecture 10: Inheritance Subclasses and superclasses
Week 8 Lecture -3 Inheritance and Polymorphism
Polymorphism 2nd Lecture
Chapter 9 Object-Oriented Programming: Inheritance
د.سناء الصايغ الفصل الأول البرمجة الشيئية
Inheritance.
Java Programming, Second Edition
Chapter 11 Inheritance and Polymorphism Part 1
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

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 Extend the functionality of an existing class. Share the commonality between two or more classes. Purpose of Inheritance Employee ClerkManagerDriver

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 Syntax class YYYY extends XXXX { } subclass superclass

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 More Examples SuperclassSubclasses StudentDiplomaStudent HDStudent ShapeCircle Rectangle Triange LoanCarLoan HomeLoan TravelLoan VehicleBus Truck

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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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.