CMSC 202 Inheritance. Aug 6, 20072 Object Relationships An object can have another object as one of instance variables. The Person class had two Date.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 14 Inheritance. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Inheritance Basics Derived classes, with.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Comp 249 Programming Methodology Chapter 7 - Inheritance – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
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
Chapter 7 Inheritance Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
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,
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
CS102--Object Oriented Programming Lecture 7: – Inheritance Copyright © 2008 Xiaoyan Li.
Chapter 8 Polymorphism and Abstract Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
CS102--Object Oriented Programming Lecture 8: – More about Inheritance When to use inheritance Relationship between classes Rules to follow Copyright ©
CS102--Object Oriented Programming Lecture 9: – Polymorphism Copyright © 2008 Xiaoyan Li.
Chapter 7 Inheritance Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Chapter 8 Polymorphism Part I.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
CS102--Object Oriented Programming Lecture 10: – Abstract Classes Copyright © 2008 Xiaoyan Li.
Computer Science I Inheritance Professor Evan Korth New York University.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
Chapter 7 Inheritance Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CMSC 202 Inheritance II. Version 10/102 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
Chapter 8 Polymorphism and Abstract Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CMSC 202 Inheritance I Class Reuse with Inheritance.
Chapter 8 Inheritance Part 1. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
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.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
Coming up: Inheritance
Creating Classes from Other Classes Appendix D © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
CMSC 202 Polymorphism 2 nd Lecture. Aug 6, Topics Constructors and polymorphism The clone method Abstract methods Abstract classes.
Polymorphism 2nd Lecture
Inheritance and Polymorphism
COMP 2710 Software Construction Inheritance
Polymorphism 2nd Lecture
Polymorphism 2nd Lecture
Road Map Inheritance Class hierarchy Overriding methods Constructors
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance 2nd Lecture
Chapter 7 Inheritance Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 14 Inheritance Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Polymorphism 2nd Lecture
Comp 249 Programming Methodology
Inheritance I Class Reuse with Inheritance
Learning Objectives Inheritance Virtual Function.
Comp 249 Programming Methodology
Inheritance 2nd Lecture
CMSC 202 Inheritance.
Inheritance.
Class Reuse with Inheritance
Inheritance 2nd Lecture
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Chapter 11 Inheritance and Polymorphism Part 1
CMSC 202 Inheritance II.
Chapter 7 Inheritance.
Presentation transcript:

CMSC 202 Inheritance

Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date objects within it. This is known as the “has a” relationship. In some OOP circles, this relationship is known as “aggregation” or “composition”. An object can be a specialized version of another object.  A Car is a Vehicle  A Triangle is a Shape  A Doctor is a Person  A Student is a Person This kind of relationship is known as the “is a” relationship. In OOP, this relationship is modeled with the powerful programming technique known as inheritance.

Aug 6, Introduction to Inheritance Inheritance is one of the main techniques of object- oriented programming (OOP) Using this technique, a very general form of a class is first defined and compiled, and then more specialized versions of the class are defined by adding instance variables and methods  The specialized classes are said to inherit the methods and instance variables of the general class Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Derived Classes When designing certain classes, there is often a natural hierarchy for grouping them  In a record-keeping program for the employees of a company, there are hourly employees and salaried employees  Hourly employees can be divided into full time and part time workers  Salaried employees can be divided into those on technical staff, and those on the executive staff Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Derived Classes All employees share certain characteristics in common  All employees have a name and a hire date  The methods for setting and changing names and hire dates would be the same for all employees Some employees have specialized characteristics  Hourly employees are paid an hourly wage, while salaried employees are paid a fixed wage  The methods for calculating wages for these two different groups would be different Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Inheritance and OOP Inheritance is an abstraction for sharing similarities among classes (name and hireDate) while preserving their differences (how they get paid). Inheritance allows us to group classes into families of related types (Employees), allowing for the sharing of common operations and data.

Aug 6, Derived Classes Within Java, a class called Employee can be defined that includes all employees This class can then be used to define classes for hourly employees and salaried employees  In turn, the HourlyEmployee class can be used to define a PartTimeHourlyEmployee class, and so forth Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, A Class Hierarchy Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, The Employee Class /** Class Invariant: All objects have a name string and hire date. A name string of "No name" indicates no real name specified yet. A hire date of Jan 1, 1000 indicates no real hire date specified yet. */ public class Employee { private String name; private Date hireDate; // no-argument constructor public Employee( ) { name = "No name"; hireDate = new Date("Jan", 1, 1000); //Just a placeholder. } // alternate constructor public Employee(String theName, Date theDate){ /* code here */ } // copy constructor public Employee(Employee originalObject){ /* code here */ } (continued)

Aug 6, Employee Class // some accessors and mutators public String getName( ){ /* code here */ } public Date getHireDate( ){ /* code here */ } public void setName(String newName){ /* code here */ } public void setHireDate(Date newDate){ /* code here */ } // toString and equals public String toString( ){ /* code here */ } public boolean equals(Employee otherEmployee){ /* code here */ } } // end of Employee Class

Aug 6, Derived Classes Since an hourly employee is an employee, it is defined as a derived class of the class Employee  A derived class is defined by adding instance variables and methods to an existing class  The existing class that the derived class is built upon is called the base class  The phrase extends BaseClass must be added to the derived class definition: public class HourlyEmployee extends Employee Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, HourlyEmployee Class /** Class Invariant: All objects have a name string, hire date, nonnegative wage rate, and nonnegative number of hours worked. */ public class HourlyEmployee extends Employee { // instance variables unique to HourlyEmployee private double wageRate; private double hours; //for the month // no-argument Constructor public HourlyEmployee( ){ /* code here */} // alternative constructor public HourlyEmployee(String theName, Date theDate, double theWageRate, double theHours) { /* code here */} // copy constructor public HourlyEmployee(HourlyEmployee originalHE){ /* code here */} (continued)

Aug 6, HourlyEmployee Class // accessors and mutator specific to HourlyEmployee public double getRate( ){ /* code here */ } public double getHours( ){ /* code here */ } public double getPay( ){ /* code here */ } public void setHours(double hoursWorked){ /* code here */ } public void setRate(double newWageRate){ /* code here */ } // toString and equals specific for HourlyEmployee public String toString( ){ /* code here */ } public boolean equals(HourlyEmployee otherHE){ /* code here */ } }// end of HourlyEmployee Class

Aug 6, Derived Classes When a derived class is defined, it is said to inherit the instance variables and methods of the base class that it extends  Class Employee defines the instance variables name and hireDate in its class definition  Class HourlyEmployee also has these instance variables, but they are not specified in its class definition  Class HourlyEmployee has additional instance variables wageRate and hours that are specified in its class definition Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Derived Classes Just as it inherits the instance variables of the class Employee, the class HourlyEmployee inherits all of its methods as well  The class HourlyEmployee inherits the methods getName, getHireDate, setName, and setHireDate from the class Employee  Any object of the class HourlyEmployee can invoke one of these methods, just like any other method Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Derived Class (Subclass) A derived class, also called a subclass, is defined by starting with another already defined class, called a base class or superclass, and adding (and/or changing) methods, instance variables, and static variables  The derived class inherits all the public methods, all the public and private instance variables, and all the public and private static variables from the base class  The derived class can add more instance variables, static variables, and/or methods Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Inherited Members A derived class automatically has all the instance variables, all the static variables, and all the public methods of the base class  Members from the base class are said to be inherited Definitions for the inherited variables and methods do not appear in the derived class  The code is reused without having to explicitly copy it, unless the creator of the derived class redefines one or more of the base class methods Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Using HourlyEmployee public static void main(String[] args) { HourlyEmployee joe = new HourlyEmployee("Joe Worker", new Date(1, 1, 2004), 50.50, 160); // getName is defined in Employee System.out.println("joe's name is " + joe.getName( )); // setName is defined in Employee System.out.println("Changing joe's name to Josephine."); joe.setName("Josephine"); // setRate( ) is specific for HourlyEmployee System.out.println(“Giving Josephine a raise”); joe.setRate( ); }

Aug 6, Overriding a Method Definition Although a derived class inherits methods from the base class, it can change or override an inherited method if necessary  In order to override a method definition, a new definition of the method is simply placed in the class definition, just like any other method that is added to the derived class Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Overriding Example Suppose the Employee class defined the method calcRaise which calculated the amount of an Employee’s raise based on years of service If the implementer of HourlyEmployee used different criteria to calculate a raise, he could implement a new version of calcRaise in the HourlyEmployee class. (continued)

Aug 6, Overriding Example public class Employee {.... double calcRaise( ) { /* code here */ } } public class HourlyEmployee extends Employee { // no calcRaise method } As we’ve seen if joe is an HourlyEmployee object, then double raise = joe.calcRaise( ); invokes the inherited calcRaise method in the Employee class.

Aug 6, Overriding Example public class Employee {.... double calcRaise( ) { /* code here */ } } public class HourlyEmployee extends Employee {.. // overriding calcRaise double calcRaise( ) { /* code here */ } } Now, if joe is an HourlyEmployee object, then double raise = joe.calcRaise( ); invokes the overridden calcRaise method in the HourlyEmployee class. To override a method in the derived class, it must have the same method signature as the method in the base class.

Aug 6, Changing the Return Type of an Overridden Method Ordinarily, the type returned may not be changed when overriding a method However, if the returned type is a class type, then it may be changed to that of any descendent class of the returned type This is known as a covariant return type  Covariant return types are new in Java 5.0; they are not allowed in earlier versions of Java Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Covariant Return Type Given the following base class: public class BaseClass {... public Employee getSomeone(int someKey)... The following is allowed in Java 5.0: public class DerivedClass extends BaseClass {... public HourlyEmployee getSomeone(int someKey)... Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Overriding Versus Overloading Do not confuse overriding a method in a derived class with overloading a method name  When a method is overridden, the new method definition given in the derived class has the exact same number and types of parameters as in the base class  When a method in a derived class has a different signature from the method in the base class, that is overloading  Note that when the derived class overloads the original method, it still inherits the original method from the base class as well (we’ll see this later) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, The final Modifier If the modifier final is placed before the definition of a method, then that method may not be redefined (overridden) in a derived class It the modifier final is placed before the definition of a class, then that class may not be used as a base class to derive other classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Pitfall: Use of Private Instance Variables from the Base Class An instance variable that is private in a base class is not accessible by name in the definition of a method in any other class, not even in a method definition of a derived class  For example, an object of the HourlyEmployee class cannot access the private instance variable hireDate by name, even though it is inherited from the Employee base class Instead, a private instance variable of the base class can only be accessed by the public accessor and mutator methods defined in that class  An object of the HourlyEmployee class can use the getHireDate or setHireDate methods to access hireDate Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Encapsulation and Inheritance Pitfall: Use of Private Instance Variables from the Base Class If private instance variables of a class were accessible in method definitions of a derived class, then anytime someone wanted to access a private instance variable, they would only need to create a derived class, and access it in a method of that class  This would allow private instance variables to be changed by mistake or in inappropriate ways (for example, by not using the base type's accessor and mutator methods only) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Pitfall: Private Methods Are Effectively Not Inherited The private methods of the base class are like private variables in terms of not being directly available However, a private method is completely unavailable, unless invoked indirectly  This is possible only if an object of a derived class invokes a public method of the base class that happens to invoke the private method This should not be a problem because private methods should just be used as helping methods  If a method is not just a helping method, then it should be public, not private Copyright © 2008 Pearson Addison-Wesley. All rights reserved