java object oriented programming encapsulation, inheritance, polymorphism (java: an eventful...

44
Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and Murtagh CS 120 Lecture 20 27 November 2012

Upload: hope-gardner

Post on 17-Jan-2016

240 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

JavaObject Oriented Programming

Encapsulation, Inheritance, Polymorphism(Java: An Eventful Approach - Ch. 17, 21.7),

Slides Credit: Bruce, Danyluk and Murtagh

CS 120 Lecture 20

27 November 2012

Page 2: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

2

Shared Features

• Common to define classes that share features– FilledRect and FramedRect

• Desirable to let classes with common features and behaviors share code– saves programmer time– improves code reliability

Page 3: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

3

Inheritance

• mechanism that provides means to share code in related classes

• already familiar...sort of– classes that extend WindowController

• inherit variables and other features from WindowController

• canvas, getContentPane(), and others defined in WindowController class

Page 4: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

4

Extension as Specialization• a class that extends another is a subclass• a class that is extended is a superclass• inheritance describes relationship between a

subclass and superclass– subclass inherits features from superclass it extends

– subclass will include every method and instance variable in superclass

– subclass may also include new features

• subclass like the superclass- but more special or specialized

Page 5: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

5

An Interactive Card Game

Note the small framed display areas in this game interface

Page 6: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

6

Framed Displays

current score “lives remaining”

time remaining start message

Page 7: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

7

Design Choices

• Could define independent class for each category of frame

or

• Better:– define class describing empty frame– extend it to define classes of specialized

frames

Page 8: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

8

Using extends

• Say we want to display text in a frame

• A FramedText class– if written from scratch, would repeat much

of FramedDisplay– define as an extension of FramedDisplay

Page 9: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

9

public class FramedText extends FramedDisplay

• extends FramedDisplay– tells Java to include all instance variables and

methods from FramedDisplay in FramedText– no need to redefine in new class

• add what we need to manipulate Text object displayed in frame

Page 10: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

10

Subclass Constructors

• often want to– inherit behavior of superclass constructor– but also do more

• write new constructor– begin with special instruction to invoke constructor

of superclass

ex. super( x, y, width, height, canvas );– add statements to perform additional work desired

Page 11: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

11

super• an invocation of super can only appear as

first command in a constructor’s body• if invocation of super not included, Java

inserts

super(); automatically

Note: Will result in error if class being extended has no parameterless constructor

Page 12: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

12

Methods of subclasses can be used in the usual way.

If we haveprivate FramedText welcome;

and executewelcome = new FramedText( “Hello”, 20, 20, 100, 30, canvas );

can legally execute

welcome.setTextSize( 24 );

and

welcome.highlight();

Page 13: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

13

Access Control

• public- can be accessed in other classes• private

– only accessible within class in which defined– restriction applies even for subclasses; private

name defined in superclass cannot be accessed in subclass

• protected– accessible in classes that extend the one in which

name defined

Page 14: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

14

Designing for Extension• easy to imagine designing subclasses of

FramedDisplay that will require info about– dimensions of parts of frame– locations of parts of frame

• in designing interface for a class, must consider– what methods would be helpful to objects outside of the

class– what would be useful to those extending the class

• prefer protected accessor methods to protected variables– access to protected variables (if not final) allows changes

that can lead to errors

Page 15: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

15

Inheritance Hierarchies

• Implement a FramedCounter class– display value of a counter (as in FramedText)– include an increment method

• FramedCounter inherits features from FramedText– includes features that FramedText inherits from

FramedDisplay

Page 16: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

16

// A FramedCounter object displays a numeric counter on// a background framed by a distinct borderpublic class FramedCounter extends FramedText {

private int counter = 0; // Current value of counter

// Create a FramedCounter object displaying 0// at the position and with the dimensions specifiedpublic FramedCounter( double x, double y, double width,

double height, DrawingCanvas canvas ) {super( “0”, x, y, width, height, canvas );

}

// Increase the counter’s value and update displaypublic void increment( int amount ) {

counter = counter + amount;message.setText( counter );positionContents();

}}

Page 17: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

17

Subclasses and Superclasses

• A is a superclass of B if– B extends A or– B extends C and A is a superclass of C

• B is a subclass of A if– B extends A or– B extends C and C is a subclass of A

Page 18: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

18

Subclass Type Compatibility

• Can assign an object to a variable as long as type of object is either– same as type of variable or– a subclass of the variable type

Page 19: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

19

Assume these variable definitions

FramedDisplay someFrame;FramedText someText;FramedCounter someCounter;

The following assignments are legal:

someFrame = new FramedDisplay( ... );someFrame = new FramedText( ... );someFrame = new FramedCounter( ... );someText = new FramedText( ... );someText = new FramedCounter( ... );someCounter = new FramedCounter( ... );

Page 20: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

20

Assuming the variable definitions:

FramedDisplay someFrame;FramedText someText;FramedCounter someCounter;

The following are also legal:

someFrame = someText;someFrame = someCounter;someText = someCounter;

Page 21: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

21

Parameter Compatibility

• Same rules apply

• Actual parameter compatible with formal parameter as long as– its type is same as type of formal

parameter or– its type is a subclass of the formal

parameter type

Page 22: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

22

Assuming the variable definitions:

FramedDisplay someFrame;FramedText someText;FramedCounter someCounter;

And a collection class with method:

public void addFrame( FramedText someText ) { ...

the following are legal for an object of the collection type

scoreDisplays.addFrame( someText );scoreDisplays.addFrame( someCounter );

Page 23: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

23

what about

someCounter = someFrame;someText = someFrame;

and

scoreDisplays.addFrame( someFrame );

Page 24: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

24

what about

someCounter = someFrame;someText = someFrame;

andscoreDisplays.addFrame( someFrame );

All Illegal

Page 25: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

25

Checking Types• Consider

someFrame = new FramedCounter( ... );someCounter = someFrame;someText = someFrame;scoreDisplays.addFrame( someFrame );

• last 3 lines still considered illegal by Java.• If programmer confident variable of correct type can introduce

type castsomeCounter = (FramedCounter) someFrame;

• To ensure type cast can be doneif ( someFrame instanceof FramedCounter ) {

someCounter = (FramedCounter) someFrame}

Page 26: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

26

Overriding Method Definitions

• Sometimes need to change behavior of methods in superclass for proper functionality in subclass.– define method in body of subclass with

same name– new method is said to override the original

method.

Page 27: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

27

The Object Class

• Java class Object is a superclass of all Java classes

• All classes inherit certain methods from Object– equals: version defined in Object compares

using == ; can override to tailor behavior of equals for a class

– toString: returns a String describing the object on which it is invoked; often useful to override.

Page 28: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

28

Accessing Overridden Methods

• sometimes want to extend- not totally change- steps performed by a method in a superclass.

• super as a means to access an overridden method from within a subclass

Page 29: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

29

Using super

Say we have added a move method to FramedDisplay

// Move the parts of the framed display by offsetspublic void move( double xoff, double yoff ) {

border.move( xoff, yoff );body.move( xoff, yoff );

}

Can override this method in FramedText as follows:

// Move the display by specified offsetspublic void move( double xoff, double yoff ) {

super.move( xoff, yoff ); // Move the body and borderpositionContents();

}

Page 30: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

30

Can refer to any nonprivate method of a superclass with

“super.methodname”in the definition of a subclass

Page 31: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

31

Dynamic Method Invocation

Say we declare

private FramedDisplay someFrame;and later execute

someFrame = new FramedText( “Follow me”, 50, 50, 80, 25, canvas );someFrame.move( 100, 50 );

Which version of move is executed?– the version in FramedDisplay?– the version in FramedText?

Page 32: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

32

Dynamic Method Invocation

Say we declare

private FramedDisplay someFrame;and later execute

someFrame = new FramedText( “Follow me”, 50, 50, 80, 25, canvas );someFrame.move( 100, 50 );

Which version of move is executed?– the version in FramedDisplay?– the version in FramedText

Page 33: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

33

• Java invokes the version of a method associated with an object’s class regardless of the type of name through which it is accessed

• process of identifying correct method is called dynamic method invocation

Page 34: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

34

A More Complex ExampleSay we define moveTo in FramedDisplaypublic void moveTo( double x, double y ) {

this move( x - border.getX(), y - border.getY() );}

• Java interprets this dynamically• invocation refers to move method of this, the object

whose moveTo was invoked

If we executeFramedText welcomeMessage = new FramedText( “Click to begin”,... );welcomeMessage.moveTo( centerX, centerY );

move in FramedText is used

Page 35: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

35

Design Suggestions• Sometimes useful to define a method of a

superclass with the expectation it will be overridden

• Consider adding the following to FramedDisplay– move, as before– setWidth, setHeight

Subclasses will need to override all of these for correct functionality

Page 36: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

36

Better Design• Define positionContents method in FramedDisplay:

protected void positionContents( ) {}

• Define move as:// Move the parts of the framed display by offsetspublic void move( double xoff, double yoff ) {

border.move( xoff, yoff );body.move( xoff, yoff );positionContents();

}• If setWidth and setHeight defined similarly, only

positionContents needs to be overridden in subclasses

Page 37: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

37

Abstract Classes and Methods

• Abstract class– provides base for defining useful subclasses

– not useful by itself

• We defined positionContents in FramedDisplay to ensure that subclasses of FramedDisplay would define it

• Unsatisfying to define an empty method• Could replace definition of positionContents with

abstract protected void positionContents() ;and make class abstract

public abstract class FramedDisplay { ...

Page 38: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

38

• Given the description of a problem,– how do you determine what classes to

define?– how do you design each class?

• Need a design methodology

Object-Oriented Design

Page 39: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

39

Object-Oriented Design

• Often software mimics the real world

• Decompose problem into objects– identify properties and behaviors– model in software

Page 40: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

40

Abstraction

• An object provides an abstraction– can use without knowing details of its

implementation– abstract away details; understand at higher level

• Follows from our use of objects in real world– can use a stopwatch without knowing exactly how

it works

• Well-designed classes provide good abstractions.

Page 41: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

41

Encapsulation

• notion of taking variables and data structures and wrapping them inside a class definition

Information Hiding

• notion of hiding details of implementation as much as possible

• Eg. Users of our Triangle class don’t need to know HOW it stores the triangle.

Page 42: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

42

Why Important?• protects variables from being modified

inappropriately by other classes

• can present classes to others for use by simply specifying interface

ex. You used objectdraw library without knowing any implementation details!

• can change details of class definition without affecting those using it.

Page 43: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

43

Writing Comments• Each class should have a class comment

– Description of class– Author’s name and date

• Each constant and variable should be commented– describe purpose (what, not how!)– parameters– return value, if any

• For long/complex methods– include comments in method– explain what is happening– balance clarity and brevity

Page 44: Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and

Student To Do’s• HW10

– Green Screen program.

– Review Lab 10 to get started.

– There is a grading criteria, check it!• Includes both style and commenting

– Try to get your web page online.

• Java Project – – Due 12/12

• Practice examples on your own!

44