Inheritance - PowerPoint PPT Presentation

1 / 42
About This Presentation
Title:

Inheritance

Description:

addCard( new Card(Card.CLUBS, r) ); addCard( new Card(Card.SPADES, r) ... Notice that 'correct' toString() is used. Notice that 'getColor' is available ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 43
Provided by: csU69
Category:
Tags: clubs | golf | inheritance | used

less

Transcript and Presenter's Notes

Title: Inheritance


1
Inheritance
2
  • Motivation
  • Some consider inheritance an essential element of
    any object-oriented program
  • We dont, but this does speak to its importance
  • Inheritance defines hierarchy of is a relations
  • We have already experienced inheritance with
    exceptions
  • NoSuchCardException extends Exception
  • Primary Advantages
  • Code reuse
  • Conceptual correspondence of Ls with Lp
  • Division of responsibility
  • Polymorphism (having many forms)
  • Primary Disadvantages
  • Yo-Yo effect
  • Compile-time

3
  • Java Inheritance (1)
  • Syntax
  • class child extends parent
  • Child is called the subclass or derived class
  • Note Can only extend ONE class
  • Single inheritance
  • Semantics
  • Inherit all public and protected members of
    parent
  • Inherits data and methods alike!
  • Must specify what is new or different than
    parent class
  • You DO NOT inherit constructors

4
  • Java Inheritance (2)
  • Access Modifiers (for real)
  • Language differences
  • Notice that protected is not the C definition
  • Classes in same package are friendly
  • Keep in mind that all classes are derived from
    Object

5
  • Example Deck of Cards (1)
  • Recall CardPile
  • Assume we change data members to protected
  • public class CardPile
  • protected java.util.Vector cards
  • protected final static int
  • DEFAULT_INITIAL_SIZE 10
  • A Deck is a Card Pile
  • public class Deck
  • extends CardPile
  • Only specify what is new
  • Constructor is new
  • Deal language is new
  • Shuffle language is new

6
  • Example Deck of Cards (2)
  • Constructor (1)
  • Build a CardPile of 52 unique cards
  • public Deck()
  • for ( int r 2 r lt Card.ACE r)
  • addCard( new Card(Card.HEARTS, r) )
  • addCard( new Card(Card.DIAMONDS, r) )
  • addCard( new Card(Card.CLUBS, r) )
  • addCard( new Card(Card.SPADES, r) )
  • Anyone see a problem????

7
  • Example Deck of Cards (3)
  • Constructor (2)
  • CardPiles cards vector never initialized
  • Use super chaining to invoke appropriate CardPile
    constructor
  • public Deck()
  • super(DECK_SIZE)
  • for ( int r 2 r lt Card.ACE r)
  • addCard( new Card(Card.HEARTS, r) )
  • addCard( new Card(Card.DIAMONDS, r) )
  • addCard( new Card(Card.CLUBS, r) )
  • addCard( new Card(Card.SPADES, r) )
  • super must be first statement in body of
    constructor
  • Use this to chain to most general local
    constructor
  • Invoke super chaining from only most general
    constructor
  • Rule of Thumb
  • Attempt to avoid processing parents data members
    in any derived class

8
  • Example Deck of Cards (4)
  • Deal
  • New natural language for handling decks
  • Can extend Deck to include new methods beyond
    what it inherits
  • public Card deal() throws
  • NoSuchCardException
  • return ( removeCard() )

9
  • Example Deck of Cards (5)
  • Shuffle
  • Randomly re-arrange cards in deck
  • Can be implemented with direct access to
    CardPiles cards vector
  • public void shuffle()
  • for(int i cards.size() - 1 i gt 0 i--)
  • int r (int)(Math.random() cards.size())
  • Card temp (Card)(cards.get(i))
  • cards.set ( i, cards.get(r) )
  • cards.set ( r, temp )
  • How could we implement strictly through
    CardPiles public interface?

10
  • Example Deck of Cards (6)
  • All the OCCF and other behaviors come for free!
  • public static void main()
  • Deck aDeck new Deck()
  • aDeck.shuffle()
  • Card aCard null
  • Card bCard null
  • try
  • aCard aDeck.deal()
  • bCard aDeck.removeCard()
  • catch (NoSuchCardException e)
  • System.out.println(aDeck)
  • Deck bDeck (Deck)(aDeck.clone())

11
  • Method Signatures (1)
  • A derived class automatically gets all visible
    methods from all ancestor classes
  • public, protected, and maybe package
  • A derived class can define own methods
  • Called extending the class methods
  • A derived class can replace inherited methods
  • Called shadowing the class methods (override)
  • New method must have exact same signature (and
    return type) as inherited version
  • A derived class can add to inherited methods
  • Called refining the class methods (override)
  • Use super.method() to invoke inherited version
    from refined version

12
  • Method Signatures (2)
  • Example Video Store Inventory (1)
  • class VideoTape
  • protected String title
  • protected int length
  • protected boolean available
  • public VideoTape( String title, int length )
  • this.title title
  • this.length length
  • this.available true
  • public String toString()
  • return ( title ", " length " min.
    available" avail )

13
  • Method Signatures (3)
  • Example Video Store Inventory (2)
  • class Movie extends VideoTape
  • protected String director
  • protected String rating
  • public Movie( String title,
  • int length,
  • String director,
  • String rating )
  • super( title, length )
  • this.director director
  • this.rating rating
  • Automatically get toString(), title,
    length, and available for free

14
  • Method Signatures (4)
  • Example Video Store Inventory (3)
  • Makes sense to include director and rating in
    string representation
  • Requires Movie to override (refine) toString()
    method
  • public String toString()
  • return ( super.toString() dir " director
    " " rating )
  • Now we have the following
  • public static void main()
  • VideoTape video
  • new VideoTape(Golf My Way, 90)
  • Movie movie
  • new Movie(Jaws,120,Speilberg,PG)
  • System.out.println( video )
  • System.out.println( movie )
  • Consider the use of final String PG PG

15
  • Dynamic Typing (1)
  • Power of inheritance is polymorphism
  • A reference to a class can hold access to any
    instance of that class or any instance of a
    descendent of that class
  • public static void main()
  • VideoTape video
  • new VideoTape(Golf My Way, 90)
  • System.out.println( video.toString() )
  • video new Movie(Jaws,120,
  • Speilberg,PG)
  • System.out.println( video.toString() )
  • Makes sense, a Movie IS A VideoTape

16
  • Dynamic Typing (2)
  • Notice that polymorphism almost gives us
    heterogeneous containers
  • public static void main()
  • Vector tapes new Vector()
  • tapes.add(new VideoTape(Golf My Way,90))
  • tapes.add(new Movie(Jaws,120,
  • Speilberg,PG))
  • for(int i 0 i lt tapes.size() i)
  • System.out.println( tapes.get(i) )
  • Object defines toString() but we have
    overridden it to act appropriately

17
  • Dynamic Typing (3)
  • Dynamic typing means the declared type (called
    the apparent type) and the actual type (called
    the dynamic type) can vary over the lifetime of a
    variable
  • Java comes with some mechanisms for testing the
    type of an object
  • Instanceof operator
  • Variable instanceof ClassName
  • if ( tape instanceof Movie )
  • Returns true if the variable holds reference to
    an instance of the class (or any descendent
    class)
  • getClass() method
  • Class getClass()
  • if(tape.getClass().equals(Movie.class))
  • Returns dynamic type of the object

18
  • Environment Chains (1)
  • Need a visual tool to understand inheritance
  • Tool should provide
  • A visual diagram representing each object in the
    system
  • An algorithm for construction of the diagrams
  • An algorithm for dynamic method invocation using
    the diagrams
  • The visual diagram notation is consistent across
    languages
  • The algorithms will vary between languages (Java
    versus C)

19
  • Environment Chains (2)
  • Example Application
  • public class Shape
  • protected Point center
  • protected Color color
  • public String toString() return Shape
  • public Color getColor() return color
  • public class Rectangle extends Shape
  • protected int length
  • protected int width
  • public String toString() return Rect
  • public class Square extends Rectangle
  • public String toString() return Square

20
  • Environment Chains (3)
  • Visual Diagram
  • public static void main()
  • Shape aShape new Shape(p, Color.RED )
  • Rectangle aRect new Rectangle(p, Color.BLUE,
  • 10, 20)
  • Square aSquare new Square(p, Color.GREEN,
    10)

21
  • Environment Chains (4)
  • Reference enters chain at apparent type of
    reference
  • public static void main()
  • aShape aSquare

22
  • Environment Chains (5)
  • Dynamic Method Invocation (1)
  • public static void main()
  • aShape aSquare
  • // Prints Square
  • System.out.println( aShape.toString() )
  • // Prints Green
  • System.out.println( aShape.getColor() )
  • Notice that correct toString() is used
  • Notice that getColor is available

23
  • Environment Chains (6)
  • Dynamic Method Invocation (2) Algorithm
  • 1) Entry point
  • Enter chain at apparent type
  • 2) Find matching signature
  • While matching signature not found (including
    type casts) and
  • current environment not NULL
  • move up one environment link
  • If current environment NULL (i.e. no matching
    signature)
  • Then halt undefined method
  • Select most specific matching signature in
    current environment
  • 3) Make sure signature is not ambiguous
  • While current environment not NULL
  • If new matching signature found with gt 1
    parameter more specific
  • Then halt - ambiguous
  • move up one environment link
  • 4) Find implementation of method
  • Drop to bottom environment link
  • While exact matching signature not found (no
    type casts)

24
  • Environment Chains (8)
  • Dynamic Method Invocation Examples (1)
  • Add the following hierarchy to our Shape example
  • public class Euclidean
  • public class Point extends Euclidean
  • public class Dimension extends Euclidean
  • Suppose Shape has the method
  • public void translate(Euclidean)
  • Suppose Rectangle has the method
  • public void translate(Point)

25
  • Environment Chains (9)
  • Dynamic Method Invocation Examples (2)
  • public static void main()
  • Euclidean e new Euclidean()
  • Point p new Point()
  • Shape shape new Shape()
  • shape.translate(e) // Runs "shape.translate(Eu
    clidean)"
  • shape.translate(p) // Runs "shape.translate(Euc
    lidean)"
  • Rectangle rect new Rectangle()
  • rect.translate(e) // Runs "shape.translate(Eucl
    idean)"
  • rect.translate(p) // Runs "rect.translate(Point
    )"
  • Shape shape2 new Rectangle()
  • shape2.translate(e) // Runs
    "shape.translate(Euclidean)"
  • shape2.translate(p) // Runs "shape.translate(Eu
    clidean)"

26
  • Environment Chains (8)
  • Dynamic Method Invocation Examples (3)
  • Now what if
  • Shape has the method
  • public void translate(Euclidean)
  • Rectangle has the methods
  • public void translate(Euclidean)
  • public void translate(Point)

27
  • Environment Chains (9)
  • Dynamic Method Invocation Examples (4)
  • public static void main()
  • Euclidean e new Euclidean()
  • Point p new Point()
  • Shape shape new Shape()
  • shape.translate(e) // Runs "shape.translate(Eu
    clidean)"
  • shape.translate(p) // Runs "shape.translate(Euc
    lidean)"
  • Rectangle rect new Rectangle()
  • rect.translate(e) // Runs "rect.translate(Eucli
    dean)"
  • rect.translate(p) // Runs "rect.translate(Point
    )"
  • Shape shape2 new Rectangle()
  • shape2.translate(e) // Runs
    "rect.translate(Euclidean)"
  • shape2.translate(p) // Runs "rect.translate(Euc
    lidean)"

28
  • Environment Chains (8)
  • Dynamic Method Invocation Examples (5)
  • Now what if
  • Shape has the method
  • public void translate(Point)
  • Rectangle has the methods
  • public void translate(Euclidean)

29
  • Environment Chains (9)
  • Dynamic Method Invocation Examples (6)
  • public static void main()
  • Euclidean e new Euclidean()
  • Point p new Point()
  • Shape shape new Shape()
  • shape.translate(e) // Undefined method
  • shape.translate(p) // Runs "shape.translate(Poi
    nt)"
  • Rectangle rect new Rectangle()
  • rect.translate(e) // Runs "rect.translate(Eucli
    dean)"
  • rect.translate(p) // Ambiguous
  • Shape shape2 new Rectangle()
  • shape2.translate(e) // Undefined method
  • shape2.translate(p) // Runs "shape.translate(Po
    int)"

30
  • Environment Chains (11)
  • Constructor Chaining (1)
  • Each class is responsible for initializing memory
    of its environment link
  • Note Constructor chaining ALWAYS occurs (even if
    implicit)
  • Constructor Chaining Algorithm
  • Build entire chain of environment links
  • Set top environment as current environment
  • While current environment is not NULL Do
  • Invoke indicated Constructor on current
    environment
  • Set current environment to child environment

31
  • Environment Chains (12)
  • Constructor Chaining Example (1)
  • public class Shape
  • public Shape()
  • System.out.println(toString())
  • public String toString() return Shape
  • public class Rectangle extends Shape
  • protected Point p
  • public Rectangle()
  • super()
  • public String toString()
  • return ( Point p super.toString() )
  • // Prints Point nullShape

32
  • super dot Revisited
  • pull model of method invocation error-prone
  • Can easily be forgotten
  • Can be pulled at wrong time
  • Alternative Template Method Design Pattern
  • Use a push model that places responsibility on
    parent, not child

33
  • Template Method DP (1)
  • UML
  • Define invariant behavior in parent
  • Define variant behavior in child
  • Parent asks child for variant behavior when needed

34
  • Template Method DP (2)
  • Example (1) super dot
  • public class Shape
  • protected Point center
  • protected Color color
  • public void draw( Graphics g )
  • g.setColor(color)
  • public class Rectangle extends Shape
  • public void draw( Graphics g )
  • super.draw(g)
  • g.fillRectangle()

35
  • Template Method DP (3)
  • Example (1) Template Method
  • public class Shape
  • protected Point center
  • protected Color color
  • public void draw( Graphics g )
  • g.setColor(color)
  • drawBorder(g)
  • protected void drawBorder(Graphics g)
  • public class Rectangle extends Shape
  • protected void drawBorder( Graphics g )
  • g.fillRectangle()

36
  • Abstract Classes (1)
  • What would happen if we just created a shape?
  • public static void main()
  • Shape aShape new Shape( p , Color.RED )
  • aShape.draw()
  • Doesnt actually display anything
  • What would we display???
  • We dont intend to have Shape instances
  • Shape is a placeholder
  • An abstract idea rather than a concrete shape

37
  • Abstract Classes (2)
  • Java allows us to say no instances allowed
  • public abstract class Shape
  • protected Point center
  • protected Color color
  • You can have Shape variables, but no shape
    instances
  • public static void main()
  • Shape aShape new Shape() // NO
  • Shape bShape new Rectangle() // YES

38
  • Abstract Classes (3)
  • What about the drawBorder method?
  • Do we really need to define an empty body?
  • What if it has a non-void return type?
  • Java provides ability to say this method must be
    defined by subclasses
  • public abstract class Shape
  • protected abstract void drawBorder()
  • Subclasses must define the drawBorder() method
  • Children can be abstract too, in which case their
    descendants must define drawBorder()
  • Do we need constructors in abstract classes?

39
  • Interfaces (1)
  • Java extends abstract classes even further
  • What if you dont want any instance variables or
    method bodies?
  • Example Cloneable
  • Example Iterator
  • Java uses interfaces to specify simply required
    behavior

40
  • Interfaces (2)
  • Example Cloneable (1)
  • public interface Cloneable
  • Object clone()
  • All methods are public abstract
  • Can contain public final static data
  • Used for shared constants

41
  • Interfaces (3)
  • Example Cloneable (2)
  • public class Shape implements Cloneable
  • public Object clone()
  • public static void main()
  • Cloneable c new Rectangle()
  • Object c2 c.clone() // Yes
  • c.draw() // No not in cloneable interface
  • A class can implement multiple interfaces
  • Instances can be manipulated through interfaces
    (any object that implements that interface)
  • Cannot declare instances of interfaces (recall,
    abstract)

42
  • Interfaces (4)
  • Interfaces allow classes to be written without
    tying to particular implementation
  • Comparable interface with compareTo()
  • Write sorting algorithm to use Comparables
  • Iterator interface
  • Allows algorithm to be independent of data
    structure
  • Programming to the interface
  • Use interfaces whenever possible for all
    variables
Write a Comment
User Comments (0)
About PowerShow.com