Inheritance - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

Inheritance

Description:

Inheritance for Construction. One of the primary goals of inheritance is code reuse ... public Shape (int ix, int iy) { x = ix; y = iy; public String describe ... – PowerPoint PPT presentation

Number of Views:67
Avg rating:3.0/5.0
Slides: 49
Provided by: michael742
Category:

less

Transcript and Presenter's Notes

Title: Inheritance


1
Inheritance
  • Cosc 2P90

2
Objects and Classes
  • What is an object?
  • It has state
  • You can perform operations on it
  • It has a unique identity
  • It is an instance of a class
  • What is a class?
  • Collection of related objects
  • Contains the same operations
  • Contains the same set of possible states

3
Classification of Languages
  • Object-based languages have
  • data abstraction, encapsulation, information
    hiding
  • E.g. Ada 83
  • Class-based languages
  • A module is a class
  • class corresponds to a type
  • class defines the properties of an object
  • object is an instance of class
  • object-oriented
  • Class bases, where classes can inherit attributes
    and operations from other classes
  • purely object-oriented vs. hybrids
  • Smalltalk, Eiffel, Java vs C, Delphi, Ada 95

4
Inheritance
  • A tool for software re-use
  • is a relationship
  • every object of subclass is conceptually also an
    object of superclass
  • Superclass (parent, base class)
  • Subclass (child, derived class)
  • extension, restriction
  • Generalization
  • A superclass is a generalization of a subclass
  • Specialization
  • A subclass is a specialization of a superclass
  • Example person, student, professor
  • inheriting attributes and operations
  • overriding operations
  • new attributes and operations
  • private vs public vs protected

5
Inheritance
6
Superclass (Java)
  • public class Person
  • protected String theName
  • public Person(String name)
  • theName name
  • // constructor
  • public String getInfo()
  • return theName
  • // getInfo
  • public String detailInfo()
  • return Details are this.getInfo()
  • // detailInfo
  • // Person
  • Person girl new Person (Sue)
  • String stra girl.getInfo()
  • String strb girl.detailInfo()

7
Subclass (Java)
public class Student extends Person private
int theRegNum public Student(String name, int
reg) super(name) theRegNum reg
// constructor public int getRegNum()
return theRegNum // getRegNum public
String getInfo() return super.getName()
, theRegNum // getInfo // Student
Student woman new Student (Mary,
2000153) String stra woman.getInfo() String
strb woman.detailInfo()
8
Inheritance
  • Java
  • syntax
  • e.g. public class Student extends Person
  • all classes are subclasses of Object
  • C
  • syntax
  • e.g. class Student public Person
  • no common superclass
  • Ada
  • tagged records
  • not class-based

9
Superclass (Ada)
  • package Persons is
  • type Person is tagged private
  • procedure personInit(p in out Person
  • name in String)
  • function getInfo(p in Person) return String
  • function detailInfo(p in Person) return
    String
  • private
  • type Person is tagged record
  • theName String
  • end record
  • end Persons
  • package body Persons is
  • end Persons

10
Subclass (Ada)
  • with Persons use Persons
  • package Students is
  • type Student is new Person with private
  • procedure studentInit(p in out Student
  • name in String
  • reg in Integer)
  • function getRegNum(p in Student) return
    Integer)
  • function getIno(p in Student) return String
  • private
  • type Student is new Person with record
  • theRegNum Integer
  • end record
  • end Students

11
Class Hierarchies
  • Example material objects
  • Inheritance is transitive
  • If a is a b, and c is a b, then c is a
    a
  • Abstract class
  • no direct instances are allowed
  • vs. concrete class class can be instantiated or
    subclassed
  • vs. Final class can be instatiated, but not
    subclassed
  • abstract operations methods without a default
    implementation
  • Overriding
  • to encode exceptions to the rule
  • Method binding
  • compile-time error
  • run-time
  • polymorphism

12
Categories of Material Objects
Material Object
Animal
Mammal
Human
Shopkeeper
Florist
Flora
13
Class Hierarchy - Material Objects
Material Objects
Animal
Plant
Flower
Mammal
Human
Dog
Platypus
Carnation
Artist
Shopkeeper
Dentist
Potter
Florist
Sallys flowers
Phyl
Kenneth
Elizabeth
Flora
Flash
14
Substitutability
  • subclass
  • class constructed using inheritance
  • subtype
  • all data fields of parent
  • all operations of parent (may be overridden)
  • indistinguishable if substituted for parent in a
    similar situation
  • subtype can be assigned as a variable of parents
    type
  • subtype can be used as if it were of parents
    type
  • substitution rule object of subclass must be
    usable in place of object from superclass

15
Forms of Inheritance
  • Inheritance is used in programming languages with
    a variety of goals
  • inheritance for specialization
  • child satisfies all specifications of parent, but
    specializes
  • e.g. Person, Student, Professor
  • inheritance for specification
  • parent is an abstract class
  • Java interface behaviour, not structure
  • inheritance for construction
  • subclass and parent are conceptually different
  • parent has functionality required by subclass

16
  • inheritance for extension
  • no modifications to parents behaviour
  • new behaviour is added
  • inheritance for limitation
  • behaviour of subclass is more restrictive than
    behaviour of parent
  • inheritance for combination
  • multiple inheritance
  • approximations in Java

17
Specialization
  • Is-a relationship between entities
  • Used to specialize a generic class
  • E.g. Student specializes person
  • E.g. Savings account specializes
  • The child class can be treated as the parent
    class
  • Substitutability
  • Common use of inheritance
  • C uses public inheritance for specialization

18
Inheritance for Specification
  • The parent class defines the behavior that is
    implemented in the child class(es)
  • The parent class itself cannot be instatiated
  • It defines the contract between users and
    implementers
  • In Java, this is done with either interfaces or
    abstract classes
  • In C, this is done using pure virtual methods

19
Specification Java Interface
  • interface ActionListener
  • public void actionPerformed (ActionEvent e)
  • class CannonWorld extends Frame
  • // a fire button listener implements the
    action
  • // listener interface
  • private class FireButtonListener implements
    ActionListener
  • public void actionPerformed (ActionEvent e)
  • // action to perform in response to button
    press

20
Specification Java Abstract Class
  • public abstract class Number
  • public abstract int intValue()
  • public abstract long longValue()
  • public abstract float floatValue()
  • public abstract double doubleValue()
  • public byte byteValue()
  • return (byte) intValue()
  • public short shortValue()
  • return (short) intValue()

21
Specification C pure virtual
  • class Number
  • public
  • virtual int intValue() const 0
  • virtual long longValue() const 0
  • virtual float floatValue() const 0
  • virtual double doubleValue() const 0
  • unsigned char byteValue() const
  • return (unsigned char) intValue()
  • short shortValue() const
  • return (short) intValue()

22
Inheritance for Construction
  • One of the primary goals of inheritance is code
    reuse
  • Inheritance can be used to reuse code between
    seemingly unrelated classes
  • implemented-in-terms-of , has-a, or uses-a
    relationship between objects

23
Construction
  • public class StackltEgt extends LinkedListltEgt
  • public void push(E item)
  • addFirst(item)
  • public boolean empty()
  • return isEmpty()
  • public E pop()
  • return removeFirst()
  • public E peek()
  • return getFirst()

24
Construction in C
  • C has the notion of private (or protected)
    inheritance
  • Inheritance is used, but the parent class is an
    implementation detail and substitutability is
    not-required
  • templatelttypename Tgt
  • class stackltTgt private linkedlistltTgt
  • void push( const T item ) addFirst(item)
  • T pop() return removeFirst(item)

25
Inheritance for Extension
  • The child class adds new functionality to the
    base, but does not change any base behavior
  • i.e. does not override any method
  • Substitutability can always be used
  • Useful for is-a or implemented-in-terms-of

26
Extension
  • The Properties class represents a persistent set
    of properties. The Properties can be saved to a
    stream or loaded from a stream. Each key and its
    corresponding value in the property list is a
    string.
  • public class Properties extends
    HashtableltObject,Objectgt
  • public void load(InputStream in) throws
    IOException
  • public void save(OutputStream out, String
    header)
  • public String getProperty(String key)
  • public Enumerationlt?gt propertyNames()
  • public void list(PrintStream out)

27
Inheritance for Limitation
  • Behavior of child class is smaller or more
    restrictive than the parent class
  • Attempts to turn-off behavior of parent classes
  • Should be avoided
  • Common when the base class is part of an external
    API

28
Limitation
  • public class SetltEgt extends LinkedListltEgt
  • // methods add, remove, contains, isEmpty and
  • // size are all inherited from LinkedList
  • public int indexOf(Object obj)
  • System.out.println(Do not use Set.indexOf)
  • return 0
  • public E get(int index)
  • System.out.println(Do not use Set.get)
  • return null

29
Benefits of Inheritance
  • software reusability
  • increased reliability
  • code sharing
  • consistency of interface
  • software components
  • rapid prototyping
  • polymorphism
  • information hiding

30
Costs of Inheritance
  • execution speed
  • general-purpose tools generally slower than
    specific tools
  • program size
  • use of library can increases size
  • Becomes difficult to remove unused code
  • message-passing overhead
  • vs. invoking procedures
  • program complexity
  • overuse of inheritance

31
Aggregation vs. Inheritance
  • aggregation
  • relationship between objects
  • one object is part of another object
  • inheritance
  • relationship between classes
  • properties of a single object
  • Common in inheritance for construction
  • example Stack and Vector

32
LinkedList class
  • public class LinkedListltEgt
  • // see if the list is empty
  • public boolean isEmpty()
  • // return size of the list
  • public int size()
  • // add element to the head of the list
  • public void addFirst(E value)
  • // return the first element in the list
  • public E getFirst()
  • // remove and return the first element
  • public E removeFirst()

33
Stack Using Composition
  • public class StackltEgt
  • private LinkedListltEgt theData
  • public Stack()
  • theData new LinkedListltEgt()
  • public boolean empty()
  • return theData.isEmpty()
  • public void push(Object item)
  • theData.addFirst(item)
  • public E peek()
  • return theData.getFirst()
  • public E pop()
  • return theData.removeFirst()

34
Stack Using Inheritance
  • class StackltEgt extends LinkedListltEgt
  • public void push (Object item)
  • addFirst(item)
  • public E peek ()
  • return getFirst()
  • public E pop ()
  • return removeFirst()

35
Comparison
  • Inheritance implies substitutability while
    composition does not
  • Composition is easier to understand
  • Inheritance extends operations (yo-yo problem)
  • Inheritance requires less writing
  • Inheritance cannot restrict operations
  • Inheritance is is-a, composition is uses-a

36
Implications of Inheritance
  • polymorphic variables
  • allocation on the heap
  • assignment and parameter passing by reference
    semantics
  • equality testing
  • memory management

37
Polymorphism
  • many forms
  • (subtype) Polymorphism is the ability for one
    type to appear (and be used) as another
  • Polymorphic variables
  • declared as a variable of one type
  • static
  • can maintain a value of that type or any subtype
  • dynamic
  • static binding vs. dynamic binding
  • example Shape

38
Shape Classes - Polymorphism
  • class Shape
  • protected int x
  • protected int y
  • public Shape (int ix, int iy)
  • x ix y iy
  • public String describe()
  • return unknown shape
  • class Square extends Shape
  • protected int side
  • public Square (int ix, int iy, int is)
  • super(ix, iy) side is
  • public String describe()
  • return square with side side
  • class Circle extends Shape
  • protected int radius
  • public Circle (int ix, int iy, int ir)
  • super(ix, iy) radius ir
  • public String describe()
  • return circle with radius radius
  • class ShapeTest
  • static public void main (String args)
  • Shape form new Circle (10,10,5)
  • System.out.println(form is
    form.describe())
  • form new Square (15,20,10)
  • System.out.println(form is
    form.describe())

39
Memory Layout
  • Stack-based memory allocations
  • tied to method entry and exit
  • offsets must be known at compile-time
  • example factorial
  • memory requirements for polymorphic variable
    determined at run-time
  • Heap-based
  • allocated when requested, i.e. at run-time
  • freed when no longer required
  • compiler needs to calculate offsets
  • memory requirements for pointers known at compile
    time
  • C
  • Whether to use the heap or the stack is up to the
    programmer
  • Using the stack to store polymorphic types can
    lead to slicing

40
Stack-Based Allocation
  • class FacTest
  • static public void main (String args)
  • int f factorial(3)
  • System.out.println(Factorial of 3 is f)
  • static public int factorial (int n)
  • int c n-1
  • int r
  • if(c gt 0)
  • r n factorial(c)
  • else
  • r 1
  • return r

41
Slicing C
  • class Shape int x int y ..
  • class Box public Shape int size
  • void someRoutine( const Shape shape )
  • Shape newShape shape ? assignment
  • newShape.x 4
  • println( shape.x )
  • println( newShape.x ) ? prints 10 then
    4
  • Box box( 10, 10, 10 )
  • someRoutine( box )

42
Assignment
  • 2 ways to handle assignment
  • Copy by reference
  • Copy actual data
  • Polymorphism makes this difficult
  • Reference semantics
  • pointer is copied
  • result 2 references to same object
  • Clone
  • Create the actual type of the object, and then
    copy
  • 2 different objects with same values
  • example Box

43
Reference Semantics (Java)
  • public class Box
  • private int value
  • public Box() value 0
  • public void setValue (int v) value v
  • public int getValue() return value
  • ...
  • Box x new Box()
  • x.setValue(7)
  • Box y x
  • y.setValue(11)
  • System.out.println(contents of x
    x.getValue())
  • System.out.println(contents of y
    y.getVallue())

44
Cloning
  • public class Box implements Cloneable
  • private int value
  • public Box () value 0
  • public void setValue (int v) value v
  • public int getValue () return value
  • public Object clone ()
  • Box b new Box()
  • b.setValue (getValue())
  • return b
  • Box x new Box()
  • x.setValue (7)
  • Box y (Box) x.clone()
  • y.SetValue (11)
  • Cloneable is an interface with a clone() method
  • Implementers should make it public
  • Note the cast to Box, having it return Object
    lends itself to polymorphic types

45
Shallow Copy vs Deep Copy
x
a box
a shape
y
a box
A shallow copy
x
a box
a shape
y
a box
a shape
A deep copy
46
Equality Test
  • Having two forms of assignment, means two forms
    of equality testing
  • Are two objects equal if they are the same
    objects, or have the same data?
  • If data, what happens if you compare a subclass
    and parent class?
  • Reference semantics (, ! in Java)
  • compare pointers
  • identity testing
  • compare to null
  • Object equality
  • .equals in Java
  • can be overridden to do equality
  • Object equality needs to satisfy some fundamental
    criteria

47
Equality Test .equals()
  • It is reflexive for any non-null reference value
    x, x.equals(x) should return true.
  • It is symmetric for any non-null reference
    values x and y, x.equals(y) should return true if
    and only if y.equals(x) returns true.
  • It is transitive for any non-null reference
    values x, y, and z, if x.equals(y) returns true
    and y.equals(z) returns true, then x.equals(z)
    should return true.
  • It is consistent for any non-null reference
    values x and y, multiple invocations of
    x.equals(y) consistently return true or
    consistently return false, provided no
    information used in equals comparisons on the
    objects is modified.
  • For any non-null reference value x,
    x.equals(null) should return false.

48
Garbage Collection
  • Stack-based memory automatically recovered at
    block (procedure) exit
  • Heap-based not necessarily automatically
    recovered
  • explicit deallocation (C) vs garbage collection
    (Java)
  • Corresponding delete operator in C required for
    each new
  • C destructors are automatically called when an
    object is deleted
Write a Comment
User Comments (0)
About PowerShow.com