Csci 490 / Engr 596Csci 490 / Engr 596Special Topics / Special ProjectsSpecial Topics / Special Projects
Software Design and Scala ProgrammingSoftware Design and Scala Programming
Spring Semester 2010Spring Semester 2010Lecture NotesLecture Notes
Understanding InheritanceUnderstanding Inheritance
This set of slides is loosely based on chapter 8 of This set of slides is loosely based on chapter 8 of Timothy Budd's textbook Timothy Budd's textbook
Understanding Object-Oriented Programming with Java, Understanding Object-Oriented Programming with Java, Updated EditionUpdated Edition
(Addison-Wesley, 2000)(Addison-Wesley, 2000)
Created: 14 August 2004, Revised for Scala 9-11 February 2010
Motivation for InheritanceMotivation for Inheritance
Use inheritance to create new software Use inheritance to create new software structures from existing software units to:structures from existing software units to:
improve productivity improve productivity enhance qualityenhance quality
1
Generality and Specialization in Generality and Specialization in Software DevelopmentSoftware Development
Conflict: Conflict: Specific projects usually require very Specific projects usually require very
specialized softwarespecialized softwareReusability usually requires very general Reusability usually requires very general
softwaresoftware
Resolution?Resolution?Inheritance allows general software to be Inheritance allows general software to be
specialized for a projectspecialized for a project
2
Abstract Idea of Inheritance Abstract Idea of Inheritance (is-a)(is-a)
3
Material Object
Non-Living Thing
Rock
Air
Living Thing
Plant
Animal
Reptile
Mammal
Human Being
Dentist Roy
Shopkeeper Flo
Writer John
CatDogPlatypus
Practical Meaning of InheritancePractical Meaning of InheritanceIn programming languages, inheritance means In programming languages, inheritance means
Data and behavior of parent class are part of child Data and behavior of parent class are part of child
Child class may include data and behavior not in parentChild class may include data and behavior not in parent
With respect to the parent class, a child class is, in With respect to the parent class, a child class is, in some sense some sense An extension – larger set of properties An extension – larger set of properties
A contraction – more specialized (restricted) objectsA contraction – more specialized (restricted) objects
4
Idealized Image of InheritanceIdealized Image of Inheritance
Consider Consider Subclass instances must possess all data areas Subclass instances must possess all data areas
of the parent of the parent Subclass instances must implement all Subclass instances must implement all
functionality of the parent functionality of the parent
Thus Thus Subclass instance should be Subclass instance should be indistinguishableindistinguishable
from parent class instance—child can be from parent class instance—child can be substituted for parent substituted for parent
5
Principle of SubstitutabilityPrinciple of Substitutability
If C is a subclass of P, instances of C can If C is a subclass of P, instances of C can be substituted for instances of P in any be substituted for instances of P in any situation with no observable effect.situation with no observable effect.
6
Subclass and SubtypeSubclass and Subtype
SubtypeSubtypeClass that satisfies principle of substitutabilityClass that satisfies principle of substitutabilitySubclass Subclass Something constructed using inheritance, whether Something constructed using inheritance, whether
or not it satisfies the principle of substitutability. or not it satisfies the principle of substitutability. The two concepts are independentThe two concepts are independentNot all subclasses are subtypes Not all subclasses are subtypes Sometimes subtypes are constructed without being Sometimes subtypes are constructed without being
subclasses subclasses
7
Forms of Inheritance Forms of Inheritance SpecializationSpecialization Child class is a special case (subtype) of parent Child class is a special case (subtype) of parent
SpecificationSpecification Parent class defines behavior implemented in the child, but not parent Parent class defines behavior implemented in the child, but not parent
ConstructionConstruction Parent class used only for its behavior -- child class is not subtype -- no Parent class used only for its behavior -- child class is not subtype -- no is-ais-a
relationship to parent relationship to parent GeneralizationGeneralization Child class modifies or overrides some methods of parent, extends the behavior to Child class modifies or overrides some methods of parent, extends the behavior to
more general kind of object more general kind of object Extension Extension Child class adds new functionality to parent, but does not change any inherited Child class adds new functionality to parent, but does not change any inherited
behavior behavior LimitationLimitation Child class limits some of the behavior of parent Child class limits some of the behavior of parent
VarianceVariance Child and parent class are variants of each other -- inheritance to allow code sharing Child and parent class are variants of each other -- inheritance to allow code sharing
-- arbitrary relationship -- arbitrary relationship CombinationCombination Child class inherits features from more than one parent -- multiple inheritance Child class inherits features from more than one parent -- multiple inheritance
8
Forms of Inheritance Forms of Inheritance SpecializationSpecialization
Child class is a special case (subtype) of parent
Most common form of inheritance Most common form of inheritance Example: Example: ProfessorProfessor is specialized form of is specialized form of EmployeeEmployee Child may override behavior of parent to specialize Child may override behavior of parent to specialize Child satisfies specification of parent in all relevant aspects Child satisfies specification of parent in all relevant aspects Preserves substitutabilityPreserves substitutability
9
Forms of InheritanceForms of Inheritance SpecificationSpecification
Parent class defines behaviorbehavior implemented in the child, but not parent Second next most common form of inheritance Second next most common form of inheritance Example: class Example: class StackInArrayStackInArray gives implementations for gives implementations for
method signatures defined in abstract class method signatures defined in abstract class StackStack Java and Scala:Java and Scala: StackInArray extends Stack StackInArray extends Stack
Example: class Example: class ArrayRankedSeqArrayRankedSeq gives implementations for gives implementations for method signatures defined in Java interface or Scala trait method signatures defined in Java interface or Scala trait RankedSequenceRankedSequence Java:Java: ArrayRankedSeq implements RankedSequence ArrayRankedSeq implements RankedSequence
Scala: Scala: ArrayRankedSeq extends RankedSequence ArrayRankedSeq extends RankedSequence
10
Forms of InheritanceForms of Inheritance Specification (continued)Specification (continued)
Parent class defines behaviorbehavior implemented in the child, but not parent …… Subclasses are realizations of incomplete abstract specification Subclasses are realizations of incomplete abstract specification Defines common interface for group of related classes Defines common interface for group of related classes Preserves substitutabilityPreserves substitutability
10
Forms of InheritanceForms of Inheritance ConstructionConstruction
Parent class used only for its behavior — child class is not subtype — no is-a relationship to parent
Sometimes used for convenience, but discouraged Sometimes used for convenience, but discouraged Example: extending Example: extending ListList class to develop class to develop SetSet, without , without
"hiding" unneeded methods "hiding" unneeded methods Example: extending a byte-based I/O stream to a stream for Example: extending a byte-based I/O stream to a stream for
handling other objects handling other objects Often violates substitutability Often violates substitutability More common in dynamically typed languages (e.g., More common in dynamically typed languages (e.g.,
Smalltalk, Ruby) than in statically typed (e.g., Java, Scala) Smalltalk, Ruby) than in statically typed (e.g., Java, Scala) Can sometimes use aggregation (composition) instead Can sometimes use aggregation (composition) instead
11
Forms of InheritanceForms of Inheritance GeneralizationGeneralization
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 Sometimes used for convenience (or necessity), but
discouraged discouraged Example: graphics Example: graphics WindowWindow generalized to generalized to ColorWindowColorWindow
(with background color) (with background color) Opposite of specialization—violates substitutability Opposite of specialization—violates substitutability Used when must build from fixed, difficult-to-modify set of Used when must build from fixed, difficult-to-modify set of
classes classes Where possible, invert class hierarchy or use aggregation Where possible, invert class hierarchy or use aggregation
12
Forms of Inheritance Forms of Inheritance ExtensionExtension
Child class adds new functionality to parent, Child class adds new functionality to parent, but does not change any inherited behaviorbut does not change any inherited behavior Useful technique to give new behaviors to existing base Useful technique to give new behaviors to existing base
class that cannot be modified class that cannot be modified Example: Example: StringSetStringSet extends extends SetSet, adding string-related , adding string-related
methods (e.g, prefix search) methods (e.g, prefix search) Preserves substitutability Preserves substitutability
13
Forms of InheritanceForms of Inheritance LimitationLimitation
Child class limits some of the behavior of Child class limits some of the behavior of parent parent Sometimes used for convenience, but strongly discouraged Sometimes used for convenience, but strongly discouraged ExampleExample:: Stack extends extends DoubleEndedQueue, ,
replacing unneeded methods to give error messages replacing unneeded methods to give error messages Violates substitutability Violates substitutability Used when must build from fixed, difficult-to-modify set Used when must build from fixed, difficult-to-modify set
of classes of classes Avoid when possible, perhaps use aggregationAvoid when possible, perhaps use aggregation
14
Forms of Inheritance Forms of Inheritance Variance Variance
Child and parent class are variants of each other—inheritance to allow code sharing—arbitrary relationship
Sometimes used for convenience, but discouraged Sometimes used for convenience, but discouraged Example: graphics Example: graphics Tablet class extending class extending Mouse to to
share similar control code share similar control code Violates substitutability Violates substitutability Better to define more general parent class like Better to define more general parent class like
PointingDevice 15
Forms of InheritanceForms of Inheritance CombinationCombination
Child class inherits features from more than one parent—multiple inheritance Example: Example: GraduateInstructor might inherit from both might inherit from both
GraduateStudent and and Faculty Often difficult to understand and to implement language Often difficult to understand and to implement language Often use to "mix-in" specification of another role or Often use to "mix-in" specification of another role or
protocol protocol
16
Forms of InheritanceForms of Inheritance Combination (continued)Combination (continued)
Child class inherits features from more than one parent—multiple inheritance …… C++ has multiple inheritance via subclassing, with some C++ has multiple inheritance via subclassing, with some
semantic difficultiessemantic difficulties Java has single inheritance via subclassing (extends), but Java has single inheritance via subclassing (extends), but
multiple inheritance for specification via interface multiple inheritance for specification via interface implementations (implements)implementations (implements)
Scala has single inheritance via subclassing and multiple Scala has single inheritance via subclassing and multiple “mix-in” inheritance of “stackable” traits (avoiding “mix-in” inheritance of “stackable” traits (avoiding semantic issues of C++)semantic issues of C++) 16
Inheritance and Assertions 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
Inheritance andInheritance and AssertionsAssertions
Interface Interface invariantsinvariants
meth()meth()
Pre-Pre-conditioncondition
Post-Post-conditioncondition
P (Parent)P (Parent) II QQ RR
C (Child)C (Child) ICIC QCQC RCRC
IC=>IIC=>I Q=>QCQ=>QC RC=>RRC=>R
strengthenstrengthen weakenweaken strengthenstrengthen
18
Trees versus Forests Trees versus Forests Two common views of class hierarchiesTwo common views of class hierarchies
Tree All classes are part of single class hierarchy All classes are part of single class hierarchy Advantage: root's functionality inherited by all objects – all have basic Advantage: root's functionality inherited by all objects – all have basic
functionality functionality Disadvantage: tight coupling of classes, large libraries for an application Disadvantage: tight coupling of classes, large libraries for an application Languages: Java's classes, Scala’s classes, Smalltalk, Objective C, Languages: Java's classes, Scala’s classes, Smalltalk, Objective C,
Delphi Object PascalDelphi Object Pascal
Forest Classes only placed in hierarchies if they have a relationship – many Classes only placed in hierarchies if they have a relationship – many
small hierarchies. small hierarchies. Advantage: smaller libraries of classes for application, less coupling Advantage: smaller libraries of classes for application, less coupling
possible possible Disadvantage: no shared functionality among all objects Disadvantage: no shared functionality among all objects Languages: Java's interfaces, Scala’s traits, C++, Apple Object Pascal Languages: Java's interfaces, Scala’s traits, C++, Apple Object Pascal 19
Tree versus ForestTree versus Forest
A
B C
D E F G
Tree
20
Trees versus ForestsTrees versus Forests
ForestForest A
B C
D E F G
X
Y Z
21
Inheritance in Java 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
Inheritance in JavaInheritance in JavaTree-structured Class HierarchyTree-structured Class Hierarchy
Root class is java.lang.Object Other classes extend exactly one other classdefault is Object
Declaration uses keyword extends after class name
23
Object
Material_Object
Non_living_Thing Living_Thing
… …
Inheritance in JavaInheritance in JavaForest-structured Interface HierarchyForest-structured Interface Hierarchy
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 public interface Queue { { // signatures of public methods // signatures of public methods
// Queues must provide// Queues must provide } } public class QueueAsLinkedList public class QueueAsLinkedList
implements Queue implements Queue { { // includes implementations// includes implementations // of the Queue methods// of the Queue methods }}
24
Inheritance in JavaInheritance in Java Visibility Modifiers for Class/Interface FeaturesVisibility Modifiers for Class/Interface Features
public features 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
Inheritance in JavaInheritance in Javapublic abstract class Stack public abstract class Stack { // extends Object by default { // extends Object by default // data definitions plus signatures and // data definitions plus signatures and // possibly implementations of methods // possibly implementations of methods } }
public class StackInArray extends Stack public class StackInArray extends Stack { // extended features plus overridden implementations { // extended features plus overridden implementations } }
public interface Queue public interface Queue { // signatures of public methods Queues must provide { // signatures of public methods Queues must provide } }
public class QueueAsLinkedList implements Queue public class QueueAsLinkedList implements Queue { // includes implementations of the Queue methods { // includes implementations of the Queue methods }} 27
Facilities of Root Class ObjectFacilities of Root Class ObjectMinimum functionality for all objects include
equals(Object obj) is is objobj the same as receiver? the same as receiver?
toString() converts the object to a string value converts the object to a string value
hashCode() return a default hashcode for the objectreturn a default hashcode for the object
getClass() getClass() return an identifier for the class of the objectreturn an identifier for the class of the object
First three above are often overridden in classes.First three above are often overridden in classes. 28
Inheritance in Scala 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) (slightly different from Java)
22
Inheritance in ScalaInheritance in ScalaTree-structured Class HierarchyTree-structured Class Hierarchy
Root class is Any Primitive value types extend AnyValAll reference object types extend AnyRef (java.lang.Object)Scala reference objects also mix-in trait ScalaObjectScala traits extend AnyRef
23
Any
AnyVal AnyRef
Java primitive values
Scala classes also have
marker trait ScalaObject
Java classes
Inheritance in ScalaInheritance in Scala
trait Philosphical {trait Philosphical { //method signatures, perhaps implementations//method signatures, perhaps implementations // perhaps data attributes// perhaps data attributes}} class Frog extends Philosphical { . . . }trait HasLegs { . . . }class Animal class Frog extends Animal with Philosphical with HasLegs { … }
27
Inheritance in ScalaInheritance in Scala Visibility Modifiers for Class/Trait FeaturesVisibility 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 anywhereprivate[X] and protected[X] provide qualified access “up to X” – gives capabilities like object private, package protected, etc.
26
Facilities of Root Classes Facilities of Root Classes Any and AnyRefAny and AnyRef
… … Look in the API documentationLook in the API documentation
28
Benefits of InheritanceBenefits of Inheritance
Software reusability (among projects) Software reusability (among projects) Code sharing (within a project) Code sharing (within a project) Increased reliability (resulting from reuse and Increased reliability (resulting from reuse and sharing of well-tested code) sharing of well-tested code) Consistency of interface (among related objects) Consistency of interface (among related objects) Rapid prototyping (quickly assemble from pre-Rapid prototyping (quickly assemble from pre-existing components) existing components) Polymorphism and frameworks (high-level Polymorphism and frameworks (high-level reusable components) reusable components) Information hiding Information hiding
29
Costs of InheritanceCosts of Inheritance
Execution speed Execution speed
Program sizeProgram size
Message-passing overheadMessage-passing overhead
Program complexityProgram complexity
30
AcknowledgementAcknowledgement
31
The development of the original Java-based The development of the original Java-based slides was supported by a grant from slides was supported by a grant from Acxiom Corporation titled “The Acxiom Acxiom Corporation titled “The Acxiom Laboratory for Software Architecture and Laboratory for Software Architecture and Component Engineering (ALSACE).”Component Engineering (ALSACE).”
Students who helped with slides—Jian Li, Yi Students who helped with slides—Jian Li, Yi Liu, Pallavi Tadepalli, etc.Liu, Pallavi Tadepalli, etc.