Abdulmotaleb El Saddik University of Ottawa

Slides:



Advertisements
Similar presentations
Chapter 8 Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
Advertisements

CS 211 Inheritance AAA.
Chapter 8 Inheritance 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
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.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
1 Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called the parent class, or.
Abstract Classes.
1 Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter Day 21. © 2007 Pearson Addison-Wesley. All rights reserved7-2 Agenda Day 20 Problem set 4 Posted  10 problems from chapters 7 & 8  Due Nov 21.
Chapter 8 Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
© 2004 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 : Inheritance Intermediate Java Programming Summer 2007.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
1 Polymorphism  A reference can be polymorphic, which can be defined as "having many forms" obj.doIt();  This line of code might execute different methods.
© 2006 Pearson Education Chapter 7: Inheritance Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William.
Chapter 7: Inheritance Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java Software.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.
COS 312 DAY 13 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress Over due – Next progress report is March 26 Assignment 4 Posted – Chap 6 & 7 – Due.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
Inheritance  Inheritance is a fundamental object-oriented technique  it enhances software design and promotes reuse  We will focus on:  deriving new.
Outline Creating Subclasses Overriding Methods Class Hierarchies Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright ©
Chapter 8 Inheritance Part 1. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Inheritance Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Chapter 8 Specialization aka Inheritance. 2 Inheritance  Review of class relationships  Uses – One class uses the services of another class, either.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
1 Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called the parent class, or.
Object Oriented Concepts Recap OOP. The four Pillars of OOP Abstraction Encapsulation Inheritance Polymorphism.
Coming up: Inheritance
© 2004 Pearson Addison-Wesley. All rights reserved April 14, 2006 Polymorphism ComS 207: Programming I (in Java) Iowa State University, SPRING 2006 Instructor:
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Chapter 8 Inheritance 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2004 Pearson Addison-Wesley. All rights reserved November 12, 2007 Inheritance ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
© 2004 Pearson Addison-Wesley. All rights reserved April 10, 2006 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Chapter 8 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
© 2004 Pearson Addison-Wesley. All rights reserved November 14, 2007 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Polymorphism November 27, 2006 ComS 207: Programming I (in Java)
Lecture 12 Inheritance.
Chapter 8 Inheritance.
COS 312 DAY 15 Tony Gauvin.
03/10/14 Inheritance-2.
Polymorphism.
03/10/14 Chapter 9 Inheritance.
Chapter 7: Inheritance Java Software Solutions
Inheritance November 10, 2006 ComS 207: Programming I (in Java)
Designing for Inheritance
Inheritance April 7, 2006 ComS 207: Programming I (in Java)
The super Reference Constructors cannot be used in child classes, even though they have public visibility Yet we often want to use the parent's constructor.
Overriding Methods & Class Hierarchies
Chapter 8 Inheritance.
Chapter 9 Polymorphism.
Chapter 8 Inheritance Part 2.
Programming in C# CHAPTER 5 & 6
Presentation transcript:

Abdulmotaleb El Saddik University of Ottawa CSI 1102 Abdulmotaleb El Saddik University of Ottawa School of Information Technology and Engineering (SITE) Multimedia Communications Research Laboratory (MCRLab) Distributed Collaborative Virtual Environments (DISCOVER) abed @ mcrlab.uottawa.ca http://www.mcrlab.uottawa.ca/

Introduction to Software Design Chapter 7: Inheritance Presentation slides for Introduction to Software Design Java Software Solutions is published by Addison-Wesley

Inheritance Another fundamental object-oriented technique is called inheritance, for organizing and creating classes and for promoting reuse Chapter 7 focuses on: deriving new classes from existing classes creating class hierarchies the protected modifier polymorphism via inheritance inheritance hierarchies for interfaces inheritance used in graphical user interfaces

Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class, or super class, or base class The derived class is called the child class or subclass. As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined for the parent class

Inheritance To tailor a derived class, the programmer can add new variables or methods, or can modify the inherited ones Software reuse is at the heart of inheritance By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software

Inheritance Inheritance relationships often are shown graphically in a class diagram, with the arrow pointing to the parent class Vehicle Car Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent

Deriving Subclasses In Java, we use the reserved word extends to establish an inheritance relationship class Car extends Vehicle { // class contents } See Words.java (page xxx) See Book.java (page xxx) See Dictionary.java (page xxx)

Words.java public class Words { /**------------------------------------------ Instantiates a derived class and invokes its inherited and local methods. ---------------------------------------------*/ public static void main (String[] args) Dictionary webster = new Dictionary (); webster.pageMessage(); webster.definitionMessage(); }

Book.java public class Book { protected int pages = 1500; //-------------------------------------------- // Prints a message about the pages of this book. //--------------------------------------------- public void pageMessage () System.out.println ("Number of pages: " + pages); }

Dictionary.java public class Dictionary extends Book { private int definitions = 52500; //--------------------------------------- // Prints a message using both local and inherited values. //---------------------------------------- public void definitionMessage () System.out.println ("Number of definitions: " + definitions); System.out.println ("Definitions per page: “ + definitions/pages); }

The Book and Dictionary Classes # pages : int + pageMessage () : void Words Dictionary - definition : int +main (args : String[]) : void + definitionMessage () : void

The protected Modifier Visibility modifiers determine which class members are inherited and which are not Variables and methods declared with public visibility are inherited; those with private visibility are not But public variables violate the principle of encapsulation There is a third visibility modifier that helps in inheritance situations: protected

The protected Modifier The protected visibility modifier allows a member of a base class to be inherited into a child protected visibility provides more encapsulation than public does However, protected visibility is not as tightly encapsulated as private visibility The details of each modifier are given in the Appendix of the text book

The super Reference Constructors are not inherited, even though they have public visibility Yet we often want to use the parent's constructor to set up the "parent's part" of the object The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor See Words2.java (page xxx) See Book2.java (page xxx) See Dictionary2.java (page xxx)

Words2.java public class Words2 { //--------------------------------------------- // Instantiates a derived class and invokes its // inherited and local methods. //------------------------------------------- public static void main (String[] args) Dictionary2 webster = new Dictionary2 (1500, 52500); webster.pageMessage(); webster.definitionMessage(); }

Book2.java public class Book2 { protected int pages; //--------------------------------------------- //Sets up the book with the specified number of pages. //------------------------------------------- public Book2 (int numPages) { pages = numPages; } // Prints a message about the pages of this book. //-------------------------------------- public void pageMessage () { System.out.println ("Number of pages: " + pages);

Dictionary2.java public class Dictionary2 extends Book2 { private int definitions; //------------------------------------------- // Sets up the dictionary with the specified number of pages // (maintained by the Book parent class) and defintions. //---------------------------------------- public Dictionary2 (int numPages, int numDefinitions) super (numPages); definitions = numDefinitions; } // Prints a message using both local and inherited values. //-------------------------------------------- public void definitionMessage () System.out.println ("Number of definitions: " + definitions); System.out.println ("Definitions per page: " + definitions/pages);

The super Reference A child’s constructor is responsible for calling the parent’s constructor The first line of a child’s constructor should use the super reference to call the parent’s constructor The super reference can be used to reference other variables and methods defined in the parent’s class

Single vs. Multiple Inheritance Basically: Java supports single inheritance, meaning that a derived class can have only one parent class Multiple inheritance, in some other languages, allows a class to be derived from two or more classes, inheriting the members of all parents Java multiple inheritance is achieved through Interfaces Collisions, such as the same variable name in two parents, have to be resolved In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead

Overriding Methods A child class can override the definition of an inherited method in favor of its own That is, a child can redefine a method that it inherits from its parent The new method must have the same signature as the parent's method, but can have a different body The type of the object executing the method determines which version of the method is invoked

Overriding Methods See Messages.java (page xxx) See Thought.java (page xxx) See Advice.java (page xxx)

Messages.java public class Messages { //--------------------------------------------- // Instatiates two objects a invokes the message method in each. public static void main (String[] args) Thought parked = new Thought(); Advice dates = new Advice(); parked.message(); dates.message(); // overridden }

Thought.java public class Thought { //------------------------------------------- // Prints a message. public void message() System.out.println ("I feel like I'm diagonally parked in a " + "parallel universe."); System.out.println(); }

Advice.java public class Advice extends Thought { //------------------------------------------- // Prints a message. This method overrides the parent's version. // It also invokes the parent's version explicitly using super. public void message() System.out.println ("Warning: Dates in calendar are closer " + "than they appear."); System.out.println(); super.message(); }

Overriding Methods and Variables Note that a parent method can be invoked explicitly using the super reference If a method is declared with the final modifier, it cannot be overridden The concept of overriding can be applied to data (called shadowing variables), but generally it should be avoided

Overloading vs. Overriding Don't confuse the concepts of overloading and overriding Overloading deals with multiple methods in the same class with the same name but different signatures Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overloading lets you define a similar operation in different ways for different data Overriding lets you define a similar operation in different ways for different object types

Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy Business RetailBusiness ServiceBusiness KMart Macys Kinkos

Class Hierarchies Two children of the same parent are called siblings Good class design puts all common features as high in the hierarchy as is reasonable An inherited member is passed continually down the line The inheritance mechanism is transitive. That is, a child class inherits from all its ancestor classes

Class Hierarchies There is no single class hierarchy that is appropriate for all situations Class hierarchies often need to be extended and modified to keep up with changes

The Object Class A class called Object is defined in the java.lang package of the Java standard class library All classes are derived from the Object class If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class Therefore, the Object class is the ultimate root of all class hierarchies

The Object Class The Object class contains a few useful methods, which are inherited by all classes For example, the toString method is defined in the Object class Every time we have defined toString, we have actually been overriding an existing definition The toString method in the Object class is defined to return a string that contains the name of the object’s class together with other information

The Object Class That’s why the println method can call toString for any object that is passed to it – all objects are guaranteed to have a toString method via inheritance See Academia.java (page xxx) See Student.java (page xxx) See GradStudent.java (page xxx)

The object Class The equals method of the Object class determines if two references are aliases We can override equals to define equality in some more appropriate way

Thank You! Ευχαριστώ Dankie WAD MAHAD SAN TAHAY GADDA GUEY

End Mark = Max (A || B) A = SUM (ASS1-4 + Midterm + FInal) B = SUM (ASS1-4 + FInal)

Abstract Classes An abstract class is a placeholder in a class hierarchy that represents a generic concept An abstract class cannot be instantiated We use the modifier abstract on the class header to declare a class as abstract abstract public class vehicle

Abstract Classes An abstract class often contains abstract methods with no definitions (like an interface does), though it doesn’t need to Unlike an interface, the abstract modifier must be applied to each abstract method An abstract class typically contains non-abstract methods with method bodies, further distinguishing abstract classes from interfaces A class declared as abstract does not need to contain abstract methods

What are Abstract Classes? The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract An abstract method cannot be defined as final (because it must be overridden) or static (because it has no definition yet) The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate E.g. Vehicle, FuelConsumption E.g. Employee, BenefitsCalculation

References and Inheritance An object reference can refer to an object of its class, or to an object of any class related to it by inheritance For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference could be used to point to a Christmas object Holiday Christmas Holiday day; day = new Christmas();

References and Inheritance Widening conversion: Assigning a predecessor object to an ancestor reference Performed by simple assignment Narrowing conversion: Assigning an ancestor object to a predecessor reference Performed with a cast Carrying this to the limit, an Object reference can be used to refer to any object An ArrayList is designed to hold Object references

Indirect Use of Noninherited Members An inherited member can be referenced directly by name in the child class, as if it were declared in the child class But even if a method or variable is not inherited by a child, it can still be accessed indirectly through parent methods See FoodAnalysis.java (page 403) See FoodItem.java (page 404) See Pizza.java (page 405)

Polymorphism: Having many forms A reference can be polymorphic, which can be defined as "having many forms“ A polymorphic reference variable can refer to different types of objects during execution Polymorphic references are resolved at run time; this is called dynamic binding Careful use of polymorphic references can lead to elegant, robust software designs Mammal pet; Horse myhorse = new Horse(); // Horse derived from Mammal // Horse is-a Mammal pet = myhorse;

Polymorphism via Interfaces An interface name can be used as the type of an object reference variable Doable obj; The obj reference can be used to point to any object of any class that implements the Doable interface The version of doThis that the following line invokes depends on the type of object that obj is referring to obj.doThis();

Polymorphism via Inheritance Suppose the Holiday class has a method called celebrate, and the Christmas class overrides it Now consider the following invocation: day.celebrate(); If day refers to a Holiday object, it invokes the Holiday version of celebrate; if it refers to a Christmas object, it invokes the Christmas version

Polymorphism via Inheritance Consider the following class hierarchy: StaffMember Volunteer Employee Executive Hourly

Polymorphism via Inheritance Now consider the task of paying all employees See Firm.java (page xxx) See Staff.java (page xxx) See StaffMember.java (page xxx) See Volunteer.java (page xxx) See Employee.java (page xxx) See Executive.java (page xxx) See Hourly.java (page xxx)

Firm.java public class Firm { public static void main (String[] args) { Staff personnel = new Staff(); personnel.payday(); } }

Staff.java public class Staff { private StaffMember[] staffList; public Staff() { staffList = new StaffMember[4]; staffList[0] = new Executive("Sam", "555-3456", 2341.07); staffList[1] = new Employee("Joe", "555-1432", 1000.00); staffList[2] = new Volunteer("Sue", "555-6567"); staffList[3] = new Volunteer("Ann", "555-7876"); } public void payday() { double amount; for (int count = 0; count < staffList.length; count++) { System.out.println(staffList[count]); amount = staffList[count].pay(); if (amount == 0) System.out.println("Thanks!"); else System.out.println("Paid: " + amount); } } }

StaffMember.java abstract public class StaffMember { protected String name; protected String phone; public StaffMember(String eName, String ePhone) { name = eName; phone = ePhone; } public String toString() { String result = "Name: " + name + "\n"; result += "Phone: " + phone; return result; } public abstract double pay(); }

Volunteer.java public class Volunteer extends StaffMember { public Volunteer (String eName, String ePhone) { super(eName, ePhone); } public double pay() { return 0.0; } }

Employee.java public class Employee extends StaffMember { protected double payRate; public Employee(String eName, String ePhone, double rate) { super(eName, ePhone); payRate = rate; } public double pay() { return payRate; } public String toString() { String result = super.toString(); return result; } }

Executive.java public class Executive extends Employee { private double bonus; public Executive(String eName, String ePhone, double rate) { super(eName, ePhone, rate); bonus = 1000; } public double pay() { double payment = super.pay() + bonus; return payment; } }

Interface Hierarchies Inheritance can be applied to interfaces as well as to classes One interface can be derived from another interface The child interface inherits all abstract methods of the parent A class implementing the child interface must define all methods from both the ancestor and child interfaces All members of an interface are public Note that class hierarchies and interface hierarchies are distinct (they do not overlap)

Polymorphism via Interfaces An interface name can be used to declare an object reference variable Interfaces allow polymorphic references in which the method that is invoked is determined by the object being referenced A class can implement multiple interfaces The interfaces are listed in the implements clause, separated by commas The class must implement all methods in all interfaces listed in the header

Speakers, Philosophers and Dogs public interface Speaker { public void speak(); public void announce (String str); } Assume Classes Philosopher and Dog both implement the Speaker interface: Speaker guest; guest = new Philosopher(); guest.speak(); speak method in Philosopher class guest = new Dog(); guest.speak; speak method in Dog class

Inheritance and GUIs An applet is an excellent example of inheritance Recall that when we define an applet, we extend the Applet class or the JApplet class The Applet and JApplet classes already handle all the details about applet creation and execution, including the interaction with a Web browser

Inheritance and GUIs Our applet classes have to deal only with issues that specifically relate to what our particular applet will do When we define certain methods, such as the paint method of an applet, we are actually overriding a method defined in the Component class, which is ultimately inherited into the Applet class or the JApplet class

GUI Components A GUI component is an object that represents a visual entity in an graphical user interface (such as a button or a text field) Components can generate events to which listener objects can respond For example, an applet is a component that can generate mouse events An applet is also a special kind of component, called a container, in which other components can be placed

The Component Class Hierarchy The Java classes that define GUI components are part of a class hierarchy Swing GUI components typically are derived from the JComponent class which is derived from the Container class which is derived from the Component class Many Swing components can serve as (limited) containers, because they are derived from the Container class

Extending Event Adapter Classes Listener classes can be created by implementing a particular interface (such as MouseListener interface) A listener also can be created by extending an event adapter class Each listener interface has a corresponding adapter class (such as the MouseAdapter class) Each adapter class implements the corresponding listener and provides empty method definitions Empty definitions for unused methods need not be provided

Summary Chapter 7 has focused on: deriving new classes from existing classes creating class hierarchies the protected modifier polymorphism via inheritance inheritance hierarchies for interfaces inheritance used in graphical user interfaces

Thank You! Ευχαριστώ Dankie WAD MAHAD SAN TAHAY GADDA GUEY