Documents
Resources
Learning Center
Upload
Plans & pricing Sign in
Sign Out

Inheritance, Polymorphism, and Abstract Classes

VIEWS: 200 PAGES: 22

Inheritance, Polymorphism, and Abstract Classes

More Info
									I2PUJ4 - Chapter 5 - Programming in the Large II

Inheritance, Polymorphism, and Abstract Classes
Rob Dempster
robd@cs.ukzn.ac.za

School of Computer Science University of KwaZulu-Natal Pietermaritzburg Campus

I2PUJ4 - Chapter 5 - Programming in the Large II – p.1/22

Abstract
This is not a paper. It is the lecture presentation slides I used to provide a framework for the lectures I presented dealing with the material covered in Section 4 of Chapter 5 of David J. Eck’s book entitled Introduction to Programming Using Java [1]. The slides were prepared A using SuSE Linux, Emacs, LTEXand Prosper. c 2005, Robert Dempster. These are free slides. There are no restrictions on using or redistributing or posting on the web a complete, unmodified copy of this material. There are some restrictions on modified copies. To be precise: Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no invariant sections, front cover text, or back cover text. The most recent version of these slides are always available, at no charge, for downloading and for on-line use at the Web address http://saturn.cs.ukzn.ac.za/ robd/javaslides/. There A you will find the LTEXsource code together with the slides in formats suitable for slide presentations (.sp.) and hand-outs (.ho.).

I2PUJ4 - Chapter 5 - Programming in the Large II – p.2/22

Inheritance and Polymorphism

In general a class represents a set of objects which share the same structure and behaviours. The class determines the structure of objects by specifying variables that are contained in each instance of the class. The class determines behaviour by providing the instance methods that express the behaviour of the objects. However, something like this can be done in most programming languages. What distinguishes OOP from traditional programming is the ability to allow classes to express the similarities among objects that share some, but not all, of their structure and behaviour. Such similarities can be expressed using inheritance and polymorphism.
I2PUJ4 - Chapter 5 - Programming in the Large II – p.3/22

Inheritance

The term inheritance refers to the fact that one class can inherit part or all of its structure and behaviour from another class. The class that does the inheriting is said to be a subclass of the class from which it inherits. If class B is a subclass of class A, we also say that class A is a superclass of class B. A subclass can add to the structure and behaviour that it inherits. It can also replace or modify inherited behaviour (though not inherited structure)

I2PUJ4 - Chapter 5 - Programming in the Large II – p.4/22

Inheritance

class B extends A { . . // additions to, and modifications of, . // stuff inherited from class A . }

Sometimes the terms derived class and base class are used instead of subclass and superclass.
I2PUJ4 - Chapter 5 - Programming in the Large II – p.5/22

Inheritance

Several classes can be declared as subclasses of the same superclass. The subclasses, which might be referred to as "sibling classes," share some structures and behaviours – namely, the ones they inherit from their common superclass. A subclass may not be declared as the subclass of more than one superclass. Java does not support multiple inheritance!!!!
I2PUJ4 - Chapter 5 - Programming in the Large II – p.6/22

Inheritance

Inheritance can also extend over several "generations" of classes. Referring to the diagram, class E is a subclass of class D which is itself a subclass of class A. In this case, class E is considered to be a subclass of class A, even though it is not a direct subclass. This in effect means that a banana can be placed into a container designed to hold fruit, provided that the Banana class is derived from the Fruit class.
I2PUJ4 - Chapter 5 - Programming in the Large II – p.7/22

Inheritance - an example

class Vehicle { int registrationNumber; Person owner; // (assuming that a Person class has been defined) void transferOwnership(Person newOwner) { . . . } } class Car extends Vehicle { int numberOfDoors; . . . } class Truck extends Vehicle { int numberOfAxels; . . . } class Motorcycle extends Vehicle { boolean hasSidecar; . . . }

I2PUJ4 - Chapter 5 - Programming in the Large II – p.8/22

Inheritance - some code

A variable that can hold a reference to an object of class A can also hold a reference to an object belonging to any subclass of A. if Car myCar = new Car(); is OK, then so to is Vehicle myVehicle = myCar; and Vehicle myVehicle = new Car();. The object "remembers" that it is in fact a Car, and not just a Vehicle. The check can be done programmatically as follows: if (myVehicle instanceof Car) ...

I2PUJ4 - Chapter 5 - Programming in the Large II – p.9/22

Inheritance - The Shape class design

Consider a program that deals with shapes drawn on the screen. Let’s say that the shapes include rectangles, ovals, and roundrects of various colours. Three classes, Rectangle, Oval, and RoundRect, could be used to represent the three types of shapes. These three classes would have a common superclass, Shape, to represent features that all three shapes have in common. The Shape class could include instance variables to represent the colour, position, and size of a shape. It could include instance methods for changing the colour, position, and size of a shape.

I2PUJ4 - Chapter 5 - Programming in the Large II – p.10/22

Inheritance - The Shape class

class Shape { Color color; // Color of the shape. (Recall that class Color // is defined in package java.awt. Assume // that this class has been imported.)

void setColor(Color newColor) { // Method to change the color of the shape. color = newColor; // change value of instance variable redraw(); // redraw shape, which will appear in new color } void redraw() { // method for drawing the shape ? ? ? // what commands should go here? } . . . // more instance variables and methods } // end of class Shape

I2PUJ4 - Chapter 5 - Programming in the Large II – p.11/22

Inheritance - The redraw() problem!

Can you spot the redraw() problem? The problem is that each different type of Shape is drawn differently. How does the computer know which Shape to draw when it executes the redraw()? The JVM executes redraw() by asking the shape object to redraw itself and every shape object knows what it has to do to redraw itself. For this to work, each subclass of Shape must override Shape’s redraw() method If oneShape is a variable of type Shape, it could refer to an object of any of the types, Rectangle, Oval, or RoundRect (as they are all a kinda Shape).

class Rectangle extends Shape { void redraw() { . . . // commands for drawing a rectangle } . . . // possibly, more methods and variables }
I2PUJ4 - Chapter 5 - Programming in the Large II – p.12/22

Polymorphism

Consider a variable oneShape of type Shape. When the statement oneShape.redraw() is executed we are sending the oneShape object a message (heard this before?) instructing it to redraw itself. It then redraws itself in the appropriate manner. The redraw() method is polymorphic.
Polymorphism

allows us to develop the Shape package knowing that we will be able to extend it with new shapes at a latter date, without having to change any of the existing code.
I2PUJ4 - Chapter 5 - Programming in the Large II – p.13/22

Polymorphism (cont’d)

Remember that an instance method is always contained in an object. The class only contains the source code for the method. When a Rectangle object is created, it contains a redraw() method. The source code for that method is in the Rectangle class. The object also contains a setColor() method. Since the Rectangle class does not define a setColor() method, the source code for the rectangle’s setColor() method comes from the superclass, Shape.
I2PUJ4 - Chapter 5 - Programming in the Large II – p.14/22

abstract methods and classes

In an earlier slide we said that each subclass of Shape class must override the redraw() method. If we declare the redraw() method in the Shape class without a body we effectively make it an abstract method. In a derived class hierarchy an abstract method must be completed at some stage before an object can be instantiated. An abstract method must also be prefixed with the abstract modifier. Any class containing an abstract method must also be be declared to be abstractby using the abstract modifier. Abstract classes provide a framework for classes that must be completed by the implementer subclassing the abstract class.
I2PUJ4 - Chapter 5 - Programming in the Large II – p.15/22

abstract methods and classes (cont’d)

In Java, every class that you declare has a superclass. If you don’t specify a superclass, then the superclass is automatically taken to be Object, a predefined class that is part of the package java.lang. The class Object itself has no superclass, but it is the only class that has this property. Every other class is thus directly or indirectly, a subclass of Object. The class Object represents very general properties that are shared by all objects - we will discuss them shortly. The Object class actually finds a use in some cases where objects of a very general sort are being manipulated.

I2PUJ4 - Chapter 5 - Programming in the Large II – p.16/22

abstract methods and classes (cont’d)

Consider a program that wants to keep track of various Shapes that have been drawn on the screen. It can store the various objects (Shapes in an instance of the standard Java class ArrayList. Suppose the ArrayListinstance is named listOfShapes. A shape, oneShape, can be added by calling the listOfShapes.add(oneShape). To retrieve a shape, we use the method listOfShapes.get(i) which returns an Object, not a Shape. WHY? However, the program may be cognisant of the shapes type. If that is the case, it could simply cast it accordingly e.g. ((Circle) listOfShapes.get(i) to manipulate it in its appropriate derived form.
I2PUJ4 - Chapter 5 - Programming in the Large II – p.17/22

abstract Extending Existing Classes

As an example, suppose you want to write a program that plays the card game, Blackjack. You can use the Card, Hand, and Deck classes developed previously. However, in the game of Blackjack it must be possible to compute the "value" of a Blackjack hand according to the rules of the game. One way to handle this is to extend the existing Hand class by adding a method that computes the Blackjack value of the hand Extending existing classes is an easy way to build on previous work. Many standard classes have been written specifically to be used as the basis for making subclasses.

I2PUJ4 - Chapter 5 - Programming in the Large II – p.18/22

abstract The Blackjack Hand - Part 1

public class BlackjackHand extends Hand { public int getBlackjackValue() { // Returns the value of this hand for the // game of Blackjack. int val; boolean ace; int cards; // The value computed for the hand. // This will be set to true if the // hand contains an ace. // Number of cards in the hand.

val = 0; ace = false; cards = getCardCount();

I2PUJ4 - Chapter 5 - Programming in the Large II – p.19/22

abstract Summary

for ( int i = 0; i < cards; i++ ) { // Add the the i-th card Card card; // The i-th card; int cardVal; // The blackjack value of the i-th card. card = getCard(i); cardVal = card.getValue(); // The normal value, 1 to 13. if (cardVal > 10) { cardVal = 10; // For a Jack, Queen, or King. } if (cardVal == 1) ace = true; // Is at least one ace. val = val + cardVal; } if ( ace == true && val + 10 <= 21 ) val = val + 10; return val; } // end getBlackjackValue() } // end class BlackjackHand

I2PUJ4 - Chapter 5 - Programming in the Large II – p.20/22

Summary

Since BlackjackHand is a subclass of Hand, an object of type BlackjackHand contains all the instance variables and instance methods defined in Hand, plus the new instance method getBlackjackValue(). Inherited variables and methods from the Hand class can also be used in the definition of BlackjackHand (except for any that are declared to be private). Extending existing classes is an easy way to build on previous work. Many standard classes have been written specifically to be used as the basis for making subclasses.
I2PUJ4 - Chapter 5 - Programming in the Large II – p.21/22

References
References
[1] Introduction to Programming Using Java, Version 4, Eck, David J., URL: http://math.hws.edu/javanotes

I2PUJ4 - Chapter 5 - Programming in the Large II – p.22/22


								
To top