based on oop with java, by d.j. barnes 1 review 4 view classes as modules encapsulate operations 4...

32
Based on OOP with Java, b y D.J. Barnes 1 Review View classes as modules Encapsulate operations View classes as struct types Encapsulate data View classes as abstract data types Encapsulate both data and operations Inheritance Defining classes in terms of other classes

Post on 22-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

Based on OOP with Java, by D.J. Barnes

1

Review

View classes as modules• Encapsulate operations

View classes as struct types• Encapsulate data

View classes as abstract data types• Encapsulate both data and operations

Inheritance• Defining classes in terms of other classes

Based on OOP with Java, by D.J. Barnes

2

Inheritance

ParkingMeter

DigitalParkingMeter AnalogParkingMeter

superclass

subclass orextended class

Based on OOP with Java, by D.J. Barnes

3

Syntax

A

B

class B extends A {....

}

Based on OOP with Java, by D.J. Barnes

4

An Example of Inheritance

Variety of heating controllers.– Basic (shared) functionality.

• On or off.

– More sophisticated functionality.• Temperature setting.

• On/off time periods.

• Possibly others.

Based on OOP with Java, by D.J. Barnes

5

HeaterController Super Classclass HeaterController { public void switchOn(){ setOn(true); }

public void switchOff(){ setOn(false); }

public boolean isOn(){ return getOn(); } ...}

Based on OOP with Java, by D.J. Barnes

6

Extending HeaterControllerclass VariableController extends HeaterController { public static final int DefaultLevel = 16, ...; public int getLevel(){ return getHeater().getTemperature(); }

public void setLevel(int level) throws RuntimeException { if((MinLevel <= level) && (level <= MaxLevel)){ getHeater().setTemperature(level); } else{ throw new RuntimeException( "Illegal level setting: "+level); } }}

Based on OOP with Java, by D.J. Barnes

7

A VariableController Object

• Use like a VariableController or HeaterController.

VariableController v = new VariableController();...// Warm up the room.v.switchOn();if(v.getLevel() == v.MinLevel){ v.setLevel(v.DefaultLevel);}...// The room is warm enough - switch the heater off.v.switchOff();

Based on OOP with Java, by D.J. Barnes

8

The Is-A Relationship

Sub class/super class often characterized in this way.– VariableController is a HeaterController.

– Circle is a Shape, Rectangle is a Shape, Square is a Rectangle.

The relationship is one way.– Rectangle is not necessarily a Square.

Based on OOP with Java, by D.J. Barnes

9

Is-A versus Has-A

A common linguistic confusion.– Often responsible for inappropriate class structures.

•VariableController has a level attribute.•VariableController is a HeaterController.

Based on OOP with Java, by D.J. Barnes

10

Issues in Inheritance

Inappropriate Inheritance. Multiple Inheritance. Downcasts and Upcasts. Inheritance for Specialization. Structural Similarity of Classes. Order of Initialization and Super Class

Constructors.

Based on OOP with Java, by D.J. Barnes

11

Inappropriate Inheritanceimport java.util.Random;

// Inappropriate inheritanceclass Die extends Random { // Return an integer in the range 1..6 public int roll(){ final int range = 6; // Use the inherited nextInt method. return 1+nextInt(range); }}

• java.util.Stack extends java.util.Vector

Based on OOP with Java, by D.J. Barnes

12

Multiple Inheritance?

A class may extend only a single class. A class may implement multiple interfaces.

– In addition to extending a single class.

An interface may extend multiple interfaces.– interface ParentTeacher extends Parent, Teacher

Based on OOP with Java, by D.J. Barnes

13

Downcasts and Upcasts

• The terminology relates to the inheritance hierarchy: up or down.

// Explicit downcasting.// Downcast: Object -> String.String s = (String)h.get(key);

// Implicit upcastingVariableController v = new VariableController();// Upcast: HC <- VC.HeaterController h = v;

Based on OOP with Java, by D.J. Barnes

14

Inheritance for Specialization

Sub classes are often more specialized versions of their super classes.– President extends Citizen

A supermarket's SellableItem class extended to add a sell-by date.– class PerishableItem extends SellableItem

Sub class has everything (and more).

Based on OOP with Java, by D.J. Barnes

15

Sub Class Initialization

The super class elements of a sub class object must be properly initialized.– VariableController on/off state.

Super class elements initialized first.– Super class constructor selection is necessary.– Argument passing must be arranged.

Based on OOP with Java, by D.J. Barnes

16

Super Class Construction (cont.)

super must be called as first statement. No-arg super class constructor called by

default.– Sub class error if the super class does not have

one.– All classes without any constructor have a

default no-arg constructor.

Based on OOP with Java, by D.J. Barnes

17

Default No-Arg Constructor

class VariableController extends HeaterController { public VariableController(int initialLevel) throws ... {

setLevel(initialLevel); } ...}

// Implicit extension of Object super class.class HeaterController extends Object { // Default (implicit) no-arg constructor. public HeaterController(){ // (Implicit) super(); } ...}

Based on OOP with Java, by D.J. Barnes

18

Access Control Issues

Inheritance means we need to revisit issues of access control.– What rights does a sub class have over its super

class members?– Classes in one package might extend classes

defined elsewhere.

Based on OOP with Java, by D.J. Barnes

19

Access Control Rules

public access is global. private access is class only.

– Sub classes have no rights.

package access is whole package. protected access is package plus sub

classes.

Based on OOP with Java, by D.J. Barnes

20

Overriding Methods

Sub class specializations often need to modify super class behavior.– The default behavior of equals only mimics

reference equality (==).– clone only creates a shallow copy, not a deep

copy.

Based on OOP with Java, by D.J. Barnes

21

class Point { ... public String toString(){

return "("+getX()+","+getY()+")"; }

public boolean equals(Object o){if(o == this){

return true;}

else if(o == null){ return false;

} else if(o instanceof Point){ Point p = (Point) o; return getX() == p.getX() && getY() == p.getY();

} else{ return false;

} } ...}

Based on OOP with Java, by D.J. Barnes

22

Rules on Overriding

Return type and arguments must match. Sub class version must not be less visible. final disregarded in matching arguments. Checked exceptions in sub class must be

compatible with those in super class.– Sub class version may throw none.

Based on OOP with Java, by D.J. Barnes

23

Method Selection

Messages always arrive at the outermost layer for non-private methods.

The outermost matching method is selected.– Compilers generate efficient code to handle

selection.

An inner version may be selected.

Based on OOP with Java, by D.J. Barnes

24

Selecting the Super Class Version of a Method

public void method(int arg){ ... // Invoke the closest super class version. super.method(arg); ...}

Based on OOP with Java, by D.J. Barnes

25

Usage of super

Distinct from usage of super in constructors.

May be used from anywhere within a method.

Only possible to select the nearest version from an inner layer.

Based on OOP with Java, by D.J. Barnes

26

Restrictions on Overriding

Overridden method may not be private. Method signatures must have identical name,

return type, argument types.– Hence, Object argument of equals.

Sub class version may be more visible. Sub class version's exceptions must be a subset

of those thrown by super class version.

Based on OOP with Java, by D.J. Barnes

27

Super Class Behavior and Overriding When you invoke a method on an object,

the actual class of the object governs which implementation is used

When you access a field, the declared type of the reference is used

Based on OOP with Java, by D.J. Barnes

28

Example

class C { public String toString(){ return "x="+getX(); } int getX(){ return defaultX;} int defaultX = 0;}

class CC1 extends C { int getX(){ return x1;} int x1 = 1;}

class CC2 extends C { int getX(){ return x2;} int x2 = 2;}

class TestExtend { public static void main(String[] s){ C o1 = new CC1(); C o2 = new CC2(); System.out.println(o1.toString()); System.out.println(o2.toString()); }}

Based on OOP with Java, by D.J. Barnes

29

Example

class C { public String toString(){ return "x="+x; } int getX(){ return x;} int x = 0;}

class CC1 extends C { int getX(){ return x;} int x = 1;}

class CC2 extends C { int getX(){ return x;} int x = 2;}

class TestExtend { public static void main(String[] s){ C o1 = new CC1(); C o2 = new CC2(); System.out.println(o1.toString()); System.out.println(o2.toString()); }}

Based on OOP with Java, by D.J. Barnes

30

Example

class C { public String toString(){ return "x="+getX(); } int getX(){ return x;} int x = 0;}

class CC1 extends C { int getX(){ return x;} int x = 1;}

class CC2 extends C { int getX(){ return x;} int x = 2;}

class TestExtend { public static void main(String[] s){ C o1 = new CC1(); C o2 = new CC2(); System.out.println(“”+o1.x+((CC1)o1).x); System.out.println(“”+o2.x+((CC2)o2).x); }}

Based on OOP with Java, by D.J. Barnes

31

Final Classes and Methods

A class defined as final cannot be sub classed.– public final class String ...– Often done to protect complex internal state

representations.

A method defined as final may not be overridden.

Based on OOP with Java, by D.J. Barnes

32

Abstract Classes and Methods

Abstract classes can be extended but not instantiated

A class that contains an abstract method must be also abstract

abstract class Name { ...}