43
1 CSA1012 - Joseph Cordina(C) 5. Inheritance Objectives By the end of this session, you should be able to : read and understand source code for derived classes derive a new class define a set of classes that behave polymorphically take advantage of Java/C#’s run-time typing

5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

1

CSA1012 - Joseph Cordina(C)

5. Inheritance

Objectives

By the end of this session, you should be able to :

• read and understand source code for derived classes

• derive a new class• define a set of classes that

behave polymorphically• take advantage of Java/C#’s

run-time typing

Page 2: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

2

CSA1012 - Joseph Cordina(C)

A Bit of Terminology

• The interface of a class is the set of methods and instances visible to the classes outside.

• The interface provides a means of access to the class and defines the properties of such a class.

• The implementation is the way the interface is implemented.

• The interface is more a design problem while the implementation is a coding problem

Page 3: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

3

CSA1012 - Joseph Cordina(C)

Introduction

• Inheritance is characteristic of object-oriented languages

• Whenever we identify the “is a” relationship between two classes, it is appropriate to derive the more specific class from the more general class:– the more general class is the

superclass, or base class or parent class.

– the more specific class is the subclass, or derived class or child class

– we “abstract” the common features and embody them in a parent class

Page 4: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

4

CSA1012 - Joseph Cordina(C)

Introduction (cont.)• The derived class:

– inherits all of the parent’s members and implementation

– optionally, adds additional members

– optionally, modifies the behaviour of some methods

• Use of inheritance produces a hierarchy of classes

Page 5: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

5

CSA1012 - Joseph Cordina(C)

Example of Inheritance• Suppose we see a need for two

types of text objects:– CompactText (emphasizes

storage efficiency rather than functionality)

– WordProcText (used for word processing; contains font information)

• We note that they will have many common features, such as a getlength() methodgiving the length of the text

Page 6: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

6

CSA1012 - Joseph Cordina(C)

Example of Inheritance (cont.)

• We start by defining a base class TextObject, which includes a getlength() method

• We then derive the two subclasses:– both inherit the getlength()

interface– either might inherit the implementation– or, override the implementation with its

own

• We can derive other subclasses later

Page 7: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

7

CSA1012 - Joseph Cordina(C)

Derivation Syntax

• In Java/C#, a derived class inherits from a base class by “extending” the base class:

public class TextObject{private Integer length;public Integer getLength() {

return length;}

}

Page 8: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

8

CSA1012 - Joseph Cordina(C)

Derivation Syntax (cont.)

[Java]public class CompactText

extends TextObject{ …}public class WordProcText

extend TextObject{ …}[C#]public class CompactText:TextObject{ …}public class WordProcText:TextObject{ …}

• A Java/C# class can derive from one base class only

• All classes automatically derive from the grand parent class java.lang.Object/System.Object

Page 9: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

9

CSA1012 - Joseph Cordina(C)

Effects of Inheritance

• Any public member of the base class is also a public member of derived classes:

WordProcText wpt = new WordProcText ();Integer len = wpt.getLength ();

• Each instance of a derived class contains all the instance variables of its base class, plus any additional ones of the derived class

Page 10: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

10

CSA1012 - Joseph Cordina(C)

Effects of Inheritance (cont.)

• Any instance of a derived class is an instance of its base class:

WordProcText wpt=new WordProcText();CompactText ct = new CompactText();TextObject tobj = wpt; // OKtobj = ct; // OK

ct = tobj; // compile-time errorct = (CompactText) tobj; // OK see

// later

Page 11: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

11

CSA1012 - Joseph Cordina(C)

Protected Access

• The following access specifierapplies to derived classes:protected

– package and subclass access

public class A

{protected Integer x;

}

Page 12: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

12

CSA1012 - Joseph Cordina(C)

Protected Access (cont.)

• Member x is accessible to:– any class that derives from class A– in the class that hosts it

Page 13: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

13

CSA1012 - Joseph Cordina(C)

Accessibility Summary

Access to class A’s membersAccess specifier Accessible by classespublic A,B,C,D,Eprotected A,B,D

default A,B,C[Java]private A

Class C

Class B

Class A

Class D

Class E

Package2Package1

extends

Page 14: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

14

CSA1012 - Joseph Cordina(C)

Overriding Methods

• Suppose class CompactStringprovides its own implementation of method getlength(), rather than inheriting class TextObject’s

• This is overriding a method:– the derived class replaces the

original implementation with its own “new and improved” versions

– it implements the method in a way that is unique to the derived class

Page 15: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

15

CSA1012 - Joseph Cordina(C)

Overriding Methods (cont.)

• Syntax example:[Java]public class TextObject {

public Integer getLength () {// TextObject’s implementation

}}public class CompactText

extends TextObject {public Integer getLength () {

// CompactText’s implementation}

}[C#]public class TextObject {

public virtual Integer getLength () {// TextObject’s implementation

}}public class CompactText:TextObject {

public override Integer getLength () { // CompactText’s implementation

}}• virtual marks the first definition, showing a method is over-

ridable. override marks a method as it overriding a parent’s method.

Page 16: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

16

CSA1012 - Joseph Cordina(C)

Dynamic Method Dispatching

• Consider the following:

TextObject tobj=new CompactText();Integer len = tobj.getLength ();

- the apparent type of the target object is TextObject, but

- the actual type of the target object is CompactText

Page 17: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

17

CSA1012 - Joseph Cordina(C)

Dynamic Method Dispatching (cont.)

• Java/C# selects the method to dispatch based on the actual type, not the apparent type, at runtime

• This is achieved since every object stores inside it the original type it was defined with

• This is another advantage of using an interpreter at runtime

Page 18: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

18

CSA1012 - Joseph Cordina(C)

Polymorphism

• Java/C#’s dynamic method dispatching supports polymorphism – ability of a program to treat objects of different related types as if they were of the same type

• Classes related by inheritance support a common interface and respond to similar method calls:– the action taken by the target appears to the

calling code to be the same– even though the different types can respond in

completely different ways– This is because an object has an identity of its

own and responds accordingly

Page 19: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

19

CSA1012 - Joseph Cordina(C)

Polymorphism (cont.)

• User code can invoke the “same” function for objects of different related types

• At run time, the program will invoke the function appropriate to each object’s type

• Each object can “do its own thing” based on its actual class

• For polymorphism to work, the method must always be defined in the base class, otherwise we cannot over-ride it.

Page 20: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

20

CSA1012 - Joseph Cordina(C)

Polymorphism

• Example: invoking the getLength()method on each element of an array of TextObject.

TextObject[] tarr = {

new EncodedText(),new WordProcText(),

new CompactText(),new TextObject()};Integer totalLen = new Integer(0);

for (Integer i = new Integer(0);i.intValue()<tarr.length;i=new Integer(i.intValue()+1))

{totalLen = new Integer(

totalLen.intValue() +

tarr[i.intValue()].getLength().intValue());

}

Page 21: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

21

CSA1012 - Joseph Cordina(C)

Polymorphism (cont.)

• The code that invokes the getLength() method ignores type differences

• We can even introduce new types of TextObject at any time, without forcing changes in calling code

• All this aids in reusability and makes code much simpler

• IMPORTANT : getLength() must be defined in the base class otherwise the compiler will report an error

Page 22: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

22

CSA1012 - Joseph Cordina(C)

The super/basekeyword

• A derived class’s version of an overridden method can call the base class’s version by using the super/basekeyword:

public class WordProcTextextends TextObject {

public Integer getlength (){

Integer len = super.getLength();…return len;

}}• In C# one just replaced super keywork with base

keyword.

Page 23: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

23

CSA1012 - Joseph Cordina(C)

The super/baseKeyword (cont)

• Note: there is no way to access a method overridden more than once:– super.super.f() is illegal– base.base.f() is illegal

• A way around it is to define a method in each super class which makes the super/base invocation.

Page 24: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

24

CSA1012 - Joseph Cordina(C)

Constructor Chaining

• Recall that constructors can be overloaded:

- what if:public class A {

A(Integer ix) { … }A(Double fx) { … }

// overloaded}public class B extends Apublic class B:A

{B (Integer ix) { … }

}

which constructor of A will be called since B is also A, thus A has to be defined properly?

Page 25: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

25

CSA1012 - Joseph Cordina(C)

Constructor Chaining (cont.)

• Use the keyword super/base to specify which of A’s constructors to call from B’s constructor:

[Java]class B extends A {

B(int ix){

super(ix) ; // calls A(int ix)

}}

[C#]class B:A {

B(int ix):base(ix)// calls A(int ix){}

}

Page 26: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

26

CSA1012 - Joseph Cordina(C)

Constructor Chaining (con’t)

• In Java, the use of super() is legal only as the first statement of a constructor

• If a constructor calls neither super() nor this() in Java, or base in C# the compiler implicitly calls the base class’s “no-parameter” constructor in the first line of the constructor:public class A{

A() { … }A (float xx) { … }

}

Page 27: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

27

CSA1012 - Joseph Cordina(C)

Constructor Chaining (con’t)

class B extends A

{B () {

… }B (float fx) {

super (fx) ; … }B (int ix){

this (); }

}

Compiler calls A() here

but not here

Page 28: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

28

CSA1012 - Joseph Cordina(C)

Constructor Chaining (Con’t)

• The appropriate overload must exist in the parent class:– recall, if you write any

constructor, the compiler does not provide the default “ no parameter” version

Page 29: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

29

CSA1012 - Joseph Cordina(C)

Constructor Chaining (con’t)

The following will produce a compiler error:class A {

int value;A(int input) { value = input; }

}class B extends A {

int myvalue;}

Page 30: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

30

CSA1012 - Joseph Cordina(C)

Abstract Classes

• A method can be declared abstract with:– the keyword abstract– no curly brackets to enclose any code

• An abstract method defines part of a class’s interface:– i.e. a method that “should” be there, but

isn’t

• A class containing one or more abstract methods:– must itself be declared abstract– cannot be instantiated– can be used only for derivation

Page 31: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

31

CSA1012 - Joseph Cordina(C)

Abstract Classes (cont.)

- a “generic” Shape object cannot exist- each sub-type has to implement its

own area() method

abstract class Shape

Class Triangle

Class Square

Class Circle

derived

abstract Float area()

Page 32: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

32

CSA1012 - Joseph Cordina(C)

Interfaces• A “pseudo-class” can be declared

with the keyword interfaceinstead of class:public interface Shape{Float area ();…}

• Such a class is completely abstract –all its methods are implicitly public abstract

• It cannot have instance data members.

• In C# there is no need to specifying the override keyword in inherited classes

Page 33: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

33

CSA1012 - Joseph Cordina(C)

Using interfaces

• An interface can be used for limited multiple inheritance with the keyword implements:

interface Shape {Float area() {…}

}

class Circle extends Drawableimplements Shape {

… }

• In C# there is no need of any special keyword, still allowing multiple inheritance using a comma separated list

Page 34: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

34

CSA1012 - Joseph Cordina(C)

Using interfaces (cont.)

class Square extends Drawableimplements Shape {

… }

Shape sp1 = new Circle (),Shape sp2 = new Square ();sp1.area();sp2.area():

Page 35: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

35

CSA1012 - Joseph Cordina(C)

Using interfaces (cont.)

• Class Circle and Squareare derived from class Drawable, but by implementing Shape, they also:– inherit Shape’s interface– can act as polymorphic instances

of Shape• With interface and implements/:, Java/C#:– supports the polymorphic features

of multiple inheritance– yet avoids the complications of

multiply implemented methods

Page 36: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

36

CSA1012 - Joseph Cordina(C)

Casting Between Class Types

• Recall that a derived class object freely converts to a base class type:

TextObject tobj=new CompactText();

• Conversion in the opposite direction is not freely permitted, but often useful, especially when converting tobj back to its original class type)

CompactText ct = tobj; // error

Page 37: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

37

CSA1012 - Joseph Cordina(C)

Casting Between Class Types (cont.)

• You may force a conversion using a cast:

CompactText ct = (CompactText) tobj;

• Casting an object to an incorrect type causes a run-time error

Page 38: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

38

CSA1012 - Joseph Cordina(C)

Summary

• Inheritance means defining a class as a specified type of another class

• One purpose of inheritance is to reuse code

• Another purpose is to support polymorphism

• Java/C# supports dynamic method dispatch at run time

Page 39: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

39

CSA1012 - Joseph Cordina(C)

Summary (cont.)

• abstract methods have no implementation

• interface types support limited multiple inheritance

• Java/C#’s run-time typing allows safe casting between class types

Page 40: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

40

CSA1012 - Joseph Cordina(C)

Quiz1. Who has access to methods

specified as protected2. When will the compiler provide an

automatic call to the parents constructor and to which constructor will this call be made

3. True or False : An abstract method will force the whole class as abstract

4. True or False : One can have MyClass ob = new MyClass() if MyClass is abstract

5. implements implements what type of class ?

6. True or False : A type cast is needed when casting a sub class to a base class

Page 41: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

41

CSA1012 - Joseph Cordina(C)

Quiz Answers

1. Same package, itself and derived classes

2. In constructors where there are no super and no this calls. The call will be made to the empty parameter constructor

3. True4. False5. Interface6. False

Page 42: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

42

CSA1012 - Joseph Cordina(C)

Exercises

1. Create an interface called SecondObserver that defines a single method, tick(). Go back to your Clock class and make class Clock implement the SecondObserver interface.

Create a new class called PrintClock that extends your Clock class. PrintClockprovides a method called toString() that produces a string representation of the current time. Test your class.

Page 43: 5. Inheritancejcor1/OOP/OOP8.pdf · Inheritance Objectives By the end of this session, you should be able to : • read and understand source code for derived classes • derive a

43

CSA1012 - Joseph Cordina(C)

Exercises (cont.)2. Create a new class called

TickingPrintClock that extends your PrintClock class.TickingPrintClock extends the tick() method to print the new time one each tick, in addition to the normal function of the method.Test your new class. You can insert the following code block to cause to your program to sleep for one second:

[Java]try {Thread.sleep (1000);

} catch (InterruptedException ie)

{ }

[C#]using System.Threading;Thread.Sleep(msec literal);