Csci 490 Engr 596 Special Topics Special Projects

  • Slides: 39
Download presentation
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala

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

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

Motivation for Inheritance Use inheritance to create new software structures from existing software units

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

Generality and Specialization in Software Development Conflict: ØSpecific projects usually require very specialized software

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

Abstract Idea of Inheritance (is-a) Non-Living Thing Material Object Rock Air Plant Reptile Living

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

Practical Meaning of Inheritance In programming languages, inheritance means Ø Data and behavior of

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

Idealized Image of Inheritance Consider ØSubclass instances must possess all data areas of the

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

Principle of Substitutability If C is a subclass of P, instances of C can

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

Subclass and Subtype ØClass that satisfies principle of substitutability Subclass ØSomething constructed using inheritance,

Subclass and 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

Forms of Inheritance Specialization Ø Child class is a special case (subtype) of parent

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

Forms of Inheritance Specialization Child class is a special case (subtype) of parent Ø

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

Forms of Inheritance Specification Parent class defines behavior implemented in the child, but not

Forms of Inheritance Specification Parent class defines behavior implemented in the child, but not parent Ø Second next most common form of inheritance Ø Example: class Stack. In. Array gives implementations for method signatures defined in abstract class Stack Java and Scala: Stack. In. Array extends Stack Ø Example: class Array. Ranked. Seq gives implementations for method signatures defined in Java interface or Scala trait Ranked. Sequence Java: Array. Ranked. Seq implements Ranked. Sequence Scala: Array. Ranked. Seq extends Ranked. Sequence 10

Forms of Inheritance Specification (continued) Parent class defines behavior implemented in the child, but

Forms of Inheritance Specification (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

Forms of Inheritance Construction Parent class used only for its behavior — child class

Forms of Inheritance Construction 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

Forms of Inheritance Generalization Child class modifies or overrides some methods of parent, extends

Forms of Inheritance Generalization 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 Color. Window (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

Forms of Inheritance Extension Child class adds new functionality to parent, but does not

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: String. Set extends Set, adding string-related methods (e. g, prefix search) Ø Preserves substitutability 13

Forms of Inheritance Limitation Child class limits some of the behavior of parent Ø

Forms of Inheritance Limitation Child class limits some of the behavior of parent Ø Sometimes used for convenience, but strongly discouraged Ø Example: Stack extends Double. Ended. Queue, 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

Forms of Inheritance Variance Child and parent class are variants of each other—inheritance to

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 Pointing. Device 15

Forms of Inheritance Combination Child class inherits features from more than one parent—multiple inheritance

Forms of Inheritance Combination Child class inherits features from more than one parent—multiple inheritance Ø Example: Graduate. Instructor might inherit from both Graduate. Student and Faculty Ø Often difficult to understand to implement language Ø Often use to "mix-in" specification of another role or protocol 16

Forms of Inheritance Combination (continued) Child class inherits features from more than one parent—multiple

Forms of Inheritance Combination (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

Inheritance and Assertions Suppose C is a subtype of P Ø P and C

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 Bounded. Stack inheriting from an unbounded Stack class Ø Give method push() a "not full" precondition – always true in Stack Ø Refine "not full" in subclass Bounded. Stack to be true or false 17

Inheritance and Assertions Interface invariants meth() Precondition Post-condition P (Parent) I Q R C

Inheritance and Assertions Interface invariants meth() Precondition Post-condition P (Parent) I Q R C (Child) IC QC RC IC=>I Q=>QC RC=>R strengthen weaken strengthen 18

Trees versus Forests Two common views of class hierarchies Tree Ø All classes are

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

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

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

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

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

Inheritance in Java Tree-structured class hierarchy (with primitive data types not in hierarchy) Forest-structured

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 Java Tree-structured Class Hierarchy Root class is java. lang. Object Other classes

Inheritance in Java Tree-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 Object Material_Object Non_living_Thing … Living_Thing … 23

Inheritance in Java Forest-structured Interface Hierarchy interface defines an interface specification implements after class

Inheritance in Java Forest-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 { // signatures of public methods // Queues must provide } public class Queue. As. Linked. List implements Queue { // includes implementations // of the Queue methods } 24

Inheritance in Java Visibility Modifiers for Class/Interface Features public features accessible from anywhere in

Inheritance in Java Visibility 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 Java public { // // // } abstract class Stack extends Object

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

Facilities of Root Class Object Minimum functionality for all objects include equals(Object obj) is

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

Inheritance in Scala Tree-structured class hierarchy (with primitives in hierarchy) Classes that extend one

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

Inheritance in Scala Tree-structured Class Hierarchy Root class is Any Primitive value types extend

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

Inheritance in Scala trait Philosphical { //method signatures, perhaps implementations // perhaps data attributes

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

Inheritance in Scala Visibility Modifiers for Class/Trait Features private features accessible from inside class

Inheritance in Scala Visibility 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

Facilities of Root Classes Any and Any. Ref … Look in the API documentation

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

Benefits of Inheritance Software reusability (among projects) Code sharing (within a project) Increased reliability

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 preexisting components) Polymorphism and frameworks (high-level reusable components) Information hiding 29

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

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

Acknowledgement The development of the original Java-based slides was supported by a grant from

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