1 / 39

Understanding Inheritance

Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes. Understanding Inheritance. This set of slides is loosely based on chapter 8 of Timothy Budd's textbook Understanding Object-Oriented Programming with Java,

majed
Download Presentation

Understanding Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Csci 490 / Engr 596Special Topics / Special ProjectsSoftware Design and Scala ProgrammingSpring Semester 2010Lecture Notes

  2. Understanding Inheritance This set of slides is loosely based on chapter 8 of Timothy Budd's textbook Understanding Object-Oriented Programming with Java, Updated Edition (Addison-Wesley, 2000) Created: 14 August 2004, Revised for Scala 9-11 February 2010

  3. Motivation for Inheritance Use inheritance to create new software structures from existing software units to: improve productivity enhance quality 1

  4. Generality and Specialization in Software Development • Conflict: • Specific projects usually require very specialized software • Reusability usually requires very general software • Resolution? • Inheritance allows general software to be specialized for a project 2

  5. Rock Non-Living Thing Air Material Object Plant Reptile Living Thing Dentist Roy Human Being Shopkeeper Flo Animal Writer John Mammal Cat Dog Platypus Abstract Idea of Inheritance (is-a) 3

  6. Practical Meaning of Inheritance In programming languages, inheritance means • Data and behavior of parent class are part of child • Child class may include data and behavior not in parent With respect to the parent class, a child class is, in some sense • An extension – larger set of properties • A contraction – more specialized (restricted) objects 4

  7. Idealized Image of Inheritance Consider • Subclass instances must possess all data areas of the parent • Subclass instances must implement all functionality of the parent Thus • Subclass instance should be indistinguishable from parent class instance—child can be substituted for parent 5

  8. Principle of Substitutability If C is a subclass of P, instances of C can be substituted for instances of P in any situation with no observable effect. 6

  9. Subclass and Subtype • Subtype • Class that satisfies principle of substitutability • Subclass • Something constructed using inheritance, whether or not it satisfies the principle of substitutability. • The two concepts are independent • Not all subclasses are subtypes • Sometimes subtypes are constructed without being subclasses 7

  10. Forms of Inheritance • Specialization • Child class is a special case (subtype) of parent • Specification • Parent class defines behavior implemented in the child, but not parent • Construction • Parent class used only for its behavior -- child class is not subtype -- no is-a relationship to parent • Generalization • Child class modifies or overrides some methods of parent, extends the behavior to more general kind of object • Extension • Child class adds new functionality to parent, but does not change any inherited behavior • Limitation • Child class limits some of the behavior of parent • Variance • Child and parent class are variants of each other -- inheritance to allow code sharing -- arbitrary relationship • Combination • Child class inherits features from more than one parent -- multiple inheritance 8

  11. Forms of Inheritance Specialization • Child class is a special case (subtype) of parent • Most common form of inheritance • Example: Professor is specialized form of Employee • Child may override behavior of parent to specialize • Child satisfies specification of parent in all relevant aspects • Preserves substitutability 9

  12. Forms of InheritanceSpecification • Parent class defines behavior implemented in the child, but not parent • Second next most common form of inheritance • Example: class StackInArray gives implementations for method signatures defined in abstract class Stack Java and Scala:StackInArray extends Stack • Example: class ArrayRankedSeq gives implementations for method signatures defined in Java interface or Scala trait RankedSequence Java: ArrayRankedSeq implements RankedSequence Scala: ArrayRankedSeq extends RankedSequence 10

  13. Forms of InheritanceSpecification (continued) • Parent class defines behavior implemented in the child, but not parent • … • Subclasses are realizations of incomplete abstract specification • Defines common interface for group of related classes • Preserves substitutability 10

  14. Forms of InheritanceConstruction • Parent class used only for its behavior — child class is not subtype — no is-a relationship to parent • Sometimes used for convenience, but discouraged • Example: extending List class to develop Set, without "hiding" unneeded methods • Example: extending a byte-based I/O stream to a stream for handling other objects • Often violates substitutability • More common in dynamically typed languages (e.g., Smalltalk, Ruby) than in statically typed (e.g., Java, Scala) • Can sometimes use aggregation (composition) instead 11

  15. Forms of InheritanceGeneralization • Child class modifies or overrides some methods of parent, extends the behavior to more general kind of object • Sometimes used for convenience (or necessity), but discouraged • Example: graphics Window generalized to ColorWindow (with background color) • Opposite of specialization—violates substitutability • Used when must build from fixed, difficult-to-modify set of classes • Where possible, invert class hierarchy or use aggregation 12

  16. Forms of Inheritance Extension • Child class adds new functionality to parent, but does not change any inherited behavior • Useful technique to give new behaviors to existing base class that cannot be modified • Example: StringSet extends Set, adding string-related methods (e.g, prefix search) • Preserves substitutability 13

  17. Forms of InheritanceLimitation • Child class limits some of the behavior of parent • Sometimes used for convenience, but strongly discouraged • Example:Stack extends DoubleEndedQueue, replacing unneeded methods to give error messages • Violates substitutability • Used when must build from fixed, difficult-to-modify set of classes • Avoid when possible, perhaps use aggregation 14

  18. Forms of Inheritance Variance • Child and parent class are variants of each other—inheritance to allow code sharing—arbitrary relationship • Sometimes used for convenience, but discouraged • Example: graphics Tablet class extending Mouse to share similar control code • Violates substitutability • Better to define more general parent class like PointingDevice 15

  19. Forms of InheritanceCombination • Child class inherits features from more than one parent—multiple inheritance • Example: GraduateInstructor might inherit from both GraduateStudent and Faculty • Often difficult to understand and to implement language • Often use to "mix-in" specification of another role or protocol 16

  20. Forms of InheritanceCombination (continued) • Child class inherits features from more than one parent—multiple inheritance • … • C++ has multiple inheritance via subclassing, with some semantic difficulties • Java has single inheritance via subclassing (extends), but multiple inheritance for specification via interface implementations (implements) • Scala has single inheritance via subclassing and multiple “mix-in” inheritance of “stackable” traits (avoiding semantic issues of C++) 16

  21. Inheritance and Assertions • Suppose C is a subtype of P • P and C have interface invariants I and IC, respectively • meth() is a public method of P with precondition Q and postcondition R • meth() in C has precondition QC and postcondition RC • Subtype C should not violate I, Q, and R • IC implies I – may strengthen invariant – extend interface and data • Q implies QC – may weaken precondition – expand valid inputs • RC implies R -- may strengthen postcondition – restrict valid outputs • Abstract preconditions can enable controlled "strengthening" of precondition • Consider BoundedStack inheriting from an unbounded Stack class • Give method push() a "not full" precondition – always true in Stack • Refine "not full" in subclass BoundedStack to be true or false 17

  22. Inheritance andAssertions 18

  23. Trees versus Forests Two common views of class hierarchies • Tree • All classes are part of single class hierarchy • Advantage: root's functionality inherited by all objects – all have basic functionality • Disadvantage: tight coupling of classes, large libraries for an application • Languages: Java's classes, Scala’s classes, Smalltalk, Objective C, Delphi Object Pascal • Forest • Classes only placed in hierarchies if they have a relationship – many small hierarchies. • Advantage: smaller libraries of classes for application, less coupling possible • Disadvantage: no shared functionality among all objects • Languages: Java's interfaces, Scala’s traits, C++, Apple Object Pascal 19

  24. A B C E F G D Tree versus Forest Tree 20

  25. A X B C Z Y E F G D Trees versus Forests Forest 21

  26. Inheritance in Java • Tree-structured class hierarchy (with primitive data types not in hierarchy) • Forest-structured interface hierarchy • Modifiers for classes/interfaces • Access modifiers for class/interface features 22

  27. Object Material_Object Non_living_Thing Living_Thing … … Inheritance in JavaTree-structured Class Hierarchy • Root class is java.lang.Object • Other classes extend exactly one other class • default is Object • Declaration uses keyword extends after class name 23

  28. interface defines an interface specification implements after class name to promise implementation of interface – inheritance for specification An interface extends zero or more other interfaces A class implements zero or more interfaces public interface Queue { // signatures of public methods // Queues must provide } public class QueueAsLinkedList implements Queue { // includes implementations // of the Queue methods } Inheritance in JavaForest-structured Interface Hierarchy 24

  29. Inheritance in JavaVisibility Modifiers for Class/Interface Features • publicfeatures accessible from anywhere in program • private features accessible from inside class only • Default-access (i.e., "friendly") features accessible from inside the current Java package • protected features accessible in package or inside any child class 26

  30. Inheritance in Java public abstract class Stack { // extends Object by default // data definitions plus signatures and // possibly implementations of methods } public class StackInArray extends Stack { // extended features plus overridden implementations } public interface Queue { // signatures of public methods Queues must provide } public class QueueAsLinkedList implements Queue { // includes implementations of the Queue methods } 27

  31. Facilities of Root Class Object Minimum functionality for all objects include • equals(Object obj) is obj the same as receiver? • toString() converts the object to a string value • hashCode() return a default hashcode for the object • getClass() return an identifier for the class of the object First three above are often overridden in classes. 28

  32. Inheritance in Scala • Tree-structured class hierarchy (with primitives in hierarchy) • Classes that extend one class and “mix-in” zero or more traits • Modifiers for classes/traits • Access modifiers for class/interface features (slightly different from Java) 22

  33. Inheritance in ScalaTree-structured Class Hierarchy Root class is Any Primitive value types extend AnyVal All reference object types extend AnyRef(java.lang.Object) Scala reference objects also mix-in trait ScalaObject Scala traits extendAnyRef Any AnyVal AnyRef Java classes Java primitive values Scala classes also have marker trait ScalaObject 23

  34. Inheritance in Scala trait Philosphical { //method signatures, perhaps implementations // perhaps data attributes } class Frog extends Philosphical { . . . } trait HasLegs { . . . } class Animal class Frog extends Animal with Philosphical with HasLegs { … } 27

  35. Inheritance in ScalaVisibility Modifiers for Class/Trait Features private features accessible from inside class only (like Java except for inner classes) protected features accessible only from subclasses (more restricted than Java) No access modifier means “public” access features accessible from anywhere private[X] and protected[X] provide qualified access “up to X” – gives capabilities like object private, package protected, etc. 26

  36. Facilities of Root Classes Any and AnyRef … Look in the API documentation 28

  37. Benefits of Inheritance • Software reusability (among projects) • Code sharing (within a project) • Increased reliability (resulting from reuse and sharing of well-tested code) • Consistency of interface (among related objects) • Rapid prototyping (quickly assemble from pre-existing components) • Polymorphism and frameworks (high-level reusable components) • Information hiding 29

  38. Costs of Inheritance • Execution speed • Program size • Message-passing overhead • Program complexity 30

  39. Acknowledgement The development of the original Java-based slides was supported by a grant from Acxiom Corporation titled “The Acxiom Laboratory for Software Architecture and Component Engineering (ALSACE).” Students who helped with slides—Jian Li, Yi Liu, Pallavi Tadepalli, etc. 31

More Related