Lecture 10 Advanced Object Programming Short

background image

Programming Languages

Lecture 10

Advanced Object Programming

R. Pełka – Wojskowa Akademia Techniczna

background image

R. Pełka: Programming Languages

2

William H. (Bill) Gates

Born Oct, 28, 1955, Seattle, Washington, U.S.

CEO of Microsoft, richest person in the world (1999)

First developed a BASIC compiler while at Harvard

Dropped out (asked to leave?) went on to develop
Microsoft

You’ve got to be willing to read other people’s
code, then write your own, then have other people
review your code

Generous to Computer Science and philanthropic in
general

Visionary, perhaps cutthroat

Microsoft in 1978
Can you find Bill
Gates ?

background image

R. Pełka: Programming Languages

3

Outline

 Inheritance – in-depth look

 Inheritance revisited – repetition from previous lectures
 Subtyping
 Substitution
 Polymorphic variables

 Advanced OO concepts

 Static dynamic types
 Overriding
 Method lookup
 Method Polymorphism
 Abstract classes
 Interfaces

background image

R. Pełka: Programming Languages

4

DoME

objects:

The DoME example

 Database of Multimedia Entertainment
 stores details about CDs and DVDs

 CD: title, artist, # tracks, playing time, got-it, comment
 DVD: title, director, playing time, got-it, comment

 allows (later) to search for information or print lists

background image

R. Pełka: Programming Languages

5

DoME classes

top half shows
fields/attribut
es

bottom half
shows
methods

background image

R. Pełka: Programming Languages

6

DoME model

classes

objects

background image

R. Pełka: Programming Languages

7

CD
source
code

public

class

CD

{

private

String title;

private

String artist;

private

String comment;

CD(String theTitle, String theArtist)
{

title = theTitle;
artist = theArtist;
comment = " ";

}

void

setComment(String newComment)

{ ... }

String getComment()
{ ... }

void

print()

{ ... }
...
}

incomplete

(comments!)

background image

R. Pełka: Programming Languages

8

DVD
source
code

public

class

DVD

{

private

String title;

private

String director;

private

String comment;

DVD(String theTitle, String theDirector)
{

title = theTitle;
director = theDirector;
comment = " ";

}

void

setComment(String newComment)

{ ... }

String getComment()
{ ... }

void

print()

{ ... }
...
}

Code of
classes CD
and DVD is
very
similar

incomplete

(comments!)

background image

R. Pełka: Programming Languages

9

class

Database {

private

ArrayList<CD> cds;

private

ArrayList<DVD> dvds;

...

public

void

list(){

for

(CD cd : cds) {

cd.print();
System.out.println();

// empty line between items

}

for

(DVD dvd : dvds) {

dvd.print();
System.out.println();

// empty line between items

}
}
}

Database source code

very similar code too

 code duplication

CD and DVD classes are very similar (large parts are

identical)

makes maintenance difficult/more work

 code duplication also in Database class

background image

R. Pełka: Programming Languages

10

Using inheritance

means

inherits or is

derived from

define one

superclass

:

Item

define

subclasses

for

CD and DVD

the superclass defines
common attributes

the subclasses

inherit

the superclass
attributes

the subclasses add own
attributes

background image

R. Pełka: Programming Languages

11

Inheritance hierarchies

All classes inherit
from
Object
(defined in the
Java language).

background image

R. Pełka: Programming Languages

12

Inheritance in Java

public class Item
{
...
}

public class CD

extends Item

{
...
}

public class DVD

extends Item

{
...
}

no change
here

change

here

background image

R. Pełka: Programming Languages

13

Superclass and subclasses

public

class

Item

{

private

String title;

private

int playingTime;

private

boolean gotIt;

private

String comment;

// constructors and methods

// omitted.

}

public class

CD

extends Item

{

private

String artist;

private

int numberOfTracks;

// constructors and methods

// omitted.

}

public class

DVD

extends Item

{

private

String director;

// constructors and methods

// omitted.

}

background image

R. Pełka: Programming Languages

14

public class

Item {

private

String title;

private

int playingTime;

private

boolean gotIt;

private

String comment;

/**

* Initialise the fields of the item.
*/

public

Item(String theTitle, int time) {

title = theTitle;
playingTime = time;
gotIt = false;
comment = "";
}

// methods omitted

}

Inheritance and constructors

background image

R. Pełka: Programming Languages

15

Inheritance and constructors

public class CD

extends Item

{
private String artist;
private int numberOfTracks;

/**

* Constructor for objects of class CD
*/

public CD(String theTitle, String theArtist,
int tracks, int time)
{

super(theTitle, time);

artist = theArtist;
numberOfTracks = tracks;
}

// methods omitted

}

Subclass constructors must
always contain a

'super'

call.

If none is written, the
compiler inserts one
(without parameters)

works only, if the superclass
has a constructor without
parameters

background image

R. Pełka: Programming Languages

16

Adding more classes

Inheritance (so far) helps
with:

Avoiding code
duplication

Code reuse

Easier maintenance

Extendibility

background image

R. Pełka: Programming Languages

17

New Database

public class

Database

{

private

ArrayList<Item> items;

/**

* Construct an empty Database.
*/

public

Database()

{
items = new ArrayList<Item>();
}

/**

* Add an item to the database.
*/

public

void addItem(Item theItem)

{
items.add(theItem);
}
...
}

background image

R. Pełka: Programming Languages

18

/**
* Print a list of all currently stored CDs and
* DVDs to the text terminal.
*/

public

void list()

{

for

(Item item : items) {

item.print();

// Print an empty line between items

System.out.println();
}
}

New Database

cntd.

avoids
code
duplicatio
n

background image

R. Pełka: Programming Languages

19

Subtyping

First, we had:

public

void addCD(CD theCD)

public

void addVideo(DVD theDVD)

Now, we have:

public

void addItem(Item theItem)

We call this method with:

DVD myDVD = new DVD(...);
database.addItem(myDVD);

background image

R. Pełka: Programming Languages

20

Subclasses and subtyping

Classes define types.

Subclasses define subtypes.

Objects of subclasses can be used
where objects of supertypes are
required.

 e.g. if someone ask us to give them a

pen, we can fulfill the request by giving
them a fountain pen or a ball pen.

 (This is called

substitution

)

background image

R. Pełka: Programming Languages

21

Subtyping and assignment

Vehicle v1 = new Vehicle();
Vehicle v2 = new Car();
Vehicle v3 = new Bicycle();

subclass

objects may be
assigned to

superclass

variables

background image

R. Pełka: Programming Languages

22

Subtyping and parameter
passing

public

class Database

{

public

void addItem(Item

theItem)
{
...
}
}

DVD dvd = new DVD(...);
CD cd = new CD(...);

database.addItem(dvd);
database.addItem(cd);

subclass

objects may be
passed to

superclass

parameters

background image

R. Pełka: Programming Languages

23

Object and class diagram

classes

objects

background image

R. Pełka: Programming Languages

24

Polymorphic variables

Object variables in Java are

polymorphic

.

Polymorphic means “of multiple forms”.(They can

hold objects of more than one type.).

Typing rule: “A variable can hold
objects of the declared type, or of
any subtype of the declared type.”

background image

R. Pełka: Programming Languages

25

Casting

Can assign subtype to supertype.

Cannot assign supertype to subtype!

Vehicle v;
Car c = new Car();
v = c;

// correct; v contains

// a car variable

c = v;

// compile-time error! even

// if v contains a car now

Casting

fixes this:

c = (Car) v;

 only ok if the vehicle

really is a Car!)

An object type in parentheses.

Used to overcome 'type loss'.

The object is not changed in any way.

A runtime check is made to ensure the
object really is of that type:

ClassCastException

if it isn't!

Use it sparingly.

background image

R. Pełka: Programming Languages

26

Polymorphic collections

All collections are polymorphic.

The elements are of type Object.

public

void

add(Object element)

public

Object get(

int

index)

All objects can be entered into collections ...

... because collections accept elements of type
Object ...

... and all classes are subtypes of Object.

Great! But what about simple types?

... remember Wrapper classes ?

background image

R. Pełka: Programming Languages

27

Wrapper classes

Primitive types (

int

,

char

, etc)

are not objects. They must be
wrapped into an object!

 This is why Java is not a “pure” OO language

Wrapper classes exist for all simple types

simple type

wrapper class

int

Integer

float

Float

char

Character

...

...

int

i = 18;

Integer iwrap =

new

Integer(i);

int

value = iwrap.intValue();

wrap the value
unwrap it

In practice,

autoboxing

and

unboxing

mean we

don't often have to do

this.

background image

R. Pełka: Programming Languages

28

Review – inheritance

Inheritance allows the definition of classes as extensions of
other classes.

Inheritance

 avoids code duplication
 allows code reuse
 simplifies the code
 simplifies maintenance and extending

Variables can hold subtype objects.

Subtypes can be used wherever supertype objects are
expected (substitution).

There is controversy in the reliability of using inheritance. It
is argued that it is safer to use interfaces (to be studied
later) instead of inheritance

background image

R. Pełka: Programming Languages

29

Abstract classes and methods

Abstract methods have

abstract

in the

signature.

Abstract methods

have no body

.

Abstract methods

make the class abstract

.

Abstract classes cannot be instantiated.

Concrete subclasses complete the
implementation.

// example of abstract class

abstract class AbstractClass {
public abstract void methodA();
void methodB() {
// ...
}
}

// example of abstract class


abstract

class AbstractClass {

public

abstract

void methodA();

void methodB() {
// ...
}
}

methodA has no body

background image

R. Pełka: Programming Languages

30

Abstract Class

 No implementation, gives the framework only

 Abstract class cannot have object
 To give the consistency when we use the method at other

out classes

 Can be used after inherit by other class

 The object can be created after all abstract methods are

implemented in subclass.

background image

R. Pełka: Programming Languages

31

Why use Abstract classes?

 Declaring a class to be abstract is good

programming practice:

 if we don't intend to create an object directly from a

class, then declaring it to be

abstract

forces us to

respect this

 if we want to create

polymorphic

methods at the lower

levels, instead of providing a method body which we
don't intend to use, declare the method to be

abstract

.

This also forces us to provide a method for the
subclasses - Java won't let us forget.

background image

R. Pełka: Programming Languages

32

Principles of OO Programming

 The four principles of object-oriented

programming are:

abstraction

- develop an abstract representation (i.e. a

class) for what you want to model, without unneeded
detail

encapsulation

- an object contains all relevant attributes

and behaviours, and its class hides the details of the
implementation behind a public interface

inheritance

- define common attributes and behaviours

at a higher level, and pass them down to subclasses

polymorphism

- allow different behaviour to be referred

to by the same name when appropriate

background image

R. Pełka: Programming Languages

33

OO modelling tips

 Think about the different things you need in your

model:

 if you think of "it" as an

idea

, make it a

class

 if you think of "it" as an

entity

, make it an

object

of

a class

 if two classes have

something in common

, put the

common things into a

superclass

 if you are not clear whether you should be using

inheritance or composition for relating A and B, try:

A

is

a B: A

inherits

from B

A is

part of

B: A is member data in B (

composition

)

background image

R. Pełka: Programming Languages

34

How should we design classes?

1. obtain a statement of the problem
2. sketch a sample scenario
3. work out what objects are involved

(do the following one class at a time:)

4. work out how those objects are meant to

behave

5.

design the interface for the class

6. define the variables
7. implement the methods
8. test the class

 the interface only shows the

public methods and data

 it does not show private data

or methods

 it does not state how the

class is implemented

 the

interface

only shows the

public methods and data

it does not show private data
or methods

it does not state how the
class is implemented

background image

R. Pełka: Programming Languages

35

Determining the interface

 before writing a class definition, determine the

interface

the set of services we offer to clients

 similarly, if defining data structures, we should

first determine the interface

stacks support a constructor and methods: push,
pop, size, isEmpty,
and top

queues offer a constructor and methods enqueue,
dequeue, size, isEmpty
and front

 people refer to the interface as the

abstract data type

background image

R. Pełka: Programming Languages

36

Data Abstraction

 if the

interface

remains the same, clients don't

need to be changed, even if the implementation
behind the interface changes

public

class Time {

private

int timeInSecs;

//public methods

}

public

class Time {

private

int hours;

private

int minutes

private

int secs;

//same public methods
//but with different
//bodies

}

background image

R. Pełka: Programming Languages

37

Java Interfaces

 Java allows us to take this one stage further, by

formally recording the interface as a

Java interface

 a Java interface is just a collection of abstract methods

(i.e. we state the signatures, but not the bodies)

public

interface

MyStack {

public int size();
public boolean isEmpty();
public Object top();
public void push(Object elt);
public Object pop();
}

states that
this is an
interface,
not a class

states that
this is an
interface,
not a class

note no
bodies for
the methods

note no
bodies for
the methods

background image

R. Pełka: Programming Languages

38

Interfaces vs classes

 a

class

definition can contain instance/class

variables and instance/class methods, including
both the signature and the body

 a Java

interface

contains only the signatures of

public instance methods (and named constants)

 a Java interface acts like a specification

it says what it means to be e.g. a stack

to be a stack, an object must offer at least those methods
in its public interface

background image

R. Pełka: Programming Languages

39

Using Java interfaces

 Java allows us to tell the compiler that a class will

implement an

interface

 regard it as a contract stating that you will meet the

specification

 any class that implements an interface must provide

implementations of the public methods (or it must
be abstract, and its subclasses provide them)

 the compiler will check, and if the bodies are not

provided, it won't compile

background image

R. Pełka: Programming Languages

40

Example

import

java.util.ArrayList;

public

class

ALStack<E>

implements

MyStack {

private

ArrayList<E> al;

public

ALStack() {

al =

new

ArrayList<E>();

}

public

int

size() {

return

al.size(); }

//and versions of isEmpty, push, pop and top ...

}

promises that we
will provide bodies for
all the MyStack methods

promises that we
will provide bodies for
all the MyStack methods

background image

R. Pełka: Programming Languages

41

Example

cntd.

public class ArrayStack

implements

MyStack {

private int capacity;
private Object[] s;
private int top = -1;

public ArrayStack(int reqdCapacity) {
capacity = reqdCapacity;
s = new Object[capacity];
}

public int size() { return top+1; }

//and versions of isEmpty, push, pop and top ...

}

background image

R. Pełka: Programming Languages

42

Interface – summary

 An

interface

is like an abstract class - it specifies

what its methods should look like, but gives no body

 if a class

implements

an interface, it is equivalent to

signing a contract saying that it will provide a body
for the specified method - Java will not compile the
program unless we provide the method definition

 we can refer to an object as though it were an object

of the interface, and invoke the interface methods

 Interfaces allow

multiple inheritance

background image

R. Pełka: Programming Languages

43

Summary

 Inheritance – in-depth look

 Inheritance revisited – repetition from previous lectures
 Subtyping
 Substitution
 Polymorphic variables

 Advanced OO concepts

 Static dynamic types
 Overriding
 Method lookup
 Method Polymorphism
 Abstract classes
 Interfaces


Document Outline


Wyszukiwarka

Podobne podstrony:
Lecture 10 Advanced object programming
CJ Lecture 10
10. Operatory arytmetyczne, Programowanie, Klasa III
lecture 10 intro to SPC
JS 10 Instrukcja for, Programowanie, instrukcje - teoria
Lecture 10 Black Death & the Peasants Revolt
2010 lecture 10 transl groups medieval theatre
2013.04.10 - 3a1 - kartk, Programowanie, Klasa III
Rachunkowosc finansowa II - 10 h UG nst - program, Zarządzanie UG, Sem. III
Lecture 07 Problem Algorithm Program
lecture 10
lecture 10 poczta
10 Wprowadzenie do programowania robotów przemysłowych
Lecture 10 DynamicDataStructures
CJ Lecture 10
Advanced Python programming
Summary of lectures 9 10

więcej podobnych podstron