Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

A REVIEW OF OBJECT-ORIENTATION

Introduction of some advanced OO topics


OBJECT-ORIENTATION
• What is it?

2
OBJECT-ORIENTED PROGRAMS
• try to model the real-world
• are collections of co-operating objects
• air traffic control system will contain aircraft objects, airport objects, flight
objects, schedule objects, etc.
• account management system will contain customer, account, transaction
objects, etc
• word processor will contain character, word, paragraph, font, format
objects, etc..

• are concerned with medium/large problems


3
ABSTRACTION AND MODULARISATION
• Abstraction
• The process of ignoring details irrelevant to the problem at hand and
emphasizing essential ones
• Thinking about a component without worrying about detail
• Taking out essentials which are common to all types
• The abstract car is composed of an abstract engine, abstract wheels…
• Other examples?
• Modularisation
• Break down into manageable pieces
• Smaller components – easier to deal with

4
OBJECT-ORIENTED SYSTEMS
• Composite, modular and organised around data
• They map to the way we see the world
• Best strategy for large, evolving software systems
• Also enforce designing before coding

5
CLASSES AND OBJECTS
• With reference to OO, what is the difference between classes and objects?

6
OBJECTS
Fundamental abstraction from which we build our systems
• Three characteristics
• State
• The fields
• Behaviour
• The methods
• Identity
• The way of referring to the object

7
CLASSES
• A class is an object template (blueprint)
• In a general sense it is the specification for an object
• In a more specific sense in Java it is the code which we write that will
produce an object at runtime – i.e. an instance of the class (instantiation)
• A class therefore specifies the features of a group of similar objects
• Defining a class specifies the features (fields, queries, commands, properties)
for members of that class
• The objects – instances of that class – are created dynamically as the system
runs
• Classes are templates
• Objects are instances of the classes
8
RELATIONSHIPS BETWEEN OBJECTS
• It is necessary that objects interact and are related/connected to other
objects
• We strive to minimize close coupling (one object heavily dependent on
another) and yet a system with objects that did not interact would not do
anything! Trade off!
• What type of relationships occur between objects?

9
TWO MAIN TYPES OF RELATIONSHIPS
• Two types of relationships:
• Association – one object has an association with another
• Composition/aggregation - a special case of association
• Inheritance - one object is a descendent of another (parent/child)

• What is the benefit of inheritance?

• What is the difference between composition and aggregation?

10
ASSOCIATION, COMPOSITION AND AGGREGATION
• Association
• object has an association with another (employee and manager) and possibly
cardinality (one to one, one to many)
• Each object can exist independently
• Aggregation
• A collection of things that can also exist independently. The collector
(example: Room) temporarily contains the collection (example: Students).
• Composition
• An object is a collection of objects that cannot function on their own
(example: a reservation needs at least contact details and a table)
• Is a close coupling but there are ways to reduce the dependence
11
INHERITANCE - SUB-CLASSING
• You have class which does almost what you want…
• Add functionality (usually) to the class to do something more specific
• Called sub-classing
• Forms relationship between two classes – inheritance or “is a”
• Dog is a mammal and inherits typical mammal attributes and behaviour
• Very powerful concept in OO

12
SUB-CLASSING
Private field – Public methods -
not inherited accessible to
or visible to clients of the class
subclass

Adds two methods


Inherits
(accessor, mutator)
getRadius
which act on the colour
& getArea
field

13
PROPERTIES OF AN OBJECT-ORIENTED LANGUAGE
• Inheritance is one of three fundamental properties of Object Oriented Language!
• Enables polymorphism

• Three fundamental properties that a language must exhibit to be considered object-oriented


• Inheritance
• Encapsulation
• Polymorphism

• Fourth property or principle is Abstraction


• What is meant by inheritance, encapsulation, polymorphism?

14
ENCAPSULATION
• Literally means “putting in a capsule” or enclosing
• In OO it can mean two related things:
• A way of restricting or controlling access to certain object components
• Bundling data with operations on the data (a class)
• Essentially make fields private and provide mutator/accessor methods
• Fields are encapsulated because access to them from outside the class
is only through methods
• We can control exactly how fields are accessed
• In Java we use keywords: private, public

15
METHOD OVERRIDING
• A class can redefine the implementation of a method it inherits – overriding
• Definition: providing an alternative implementation of an inherited
method
• methods performing the same task must have the same name in both
parent and child classes
• the runtime system will determine which version of the method it should
use from the object's type
• this is a kind of dynamic binding which allows polymorphism

16
USING INHERITANCE GIVES US POLYMORPHISM
• When a statement calls a parent method on a parent class object, but the
object is actually a child class object
• Compiler uses the static type to check validity
• No problem: child objects inherit all parent methods
• Runtime system uses the dynamic type
• If the method is overridden in child classes
• Runtime system uses dynamic type to select the appropriate version.

17
ABSTRACT CLASSES AND INTERFACES
• What is an abstract class?
• What is an interface (as used in Java)?

19
ABSTRACT CLASSES AND INTERFACES
• Java has a an abstract class and interface
• Abstract class is a class which cannot be instantiated
• Either because it is not desirable
• Or because it would not make sense (often a combination of the two)
• Interface is pure abstract class – only behaviour is defined in the form of
method signatures
• Using abstract classes and interfaces (and polymorphism) allows reduced
coupling
• Many design patterns are based around this idea

20
ABSTRACT CLASS
• Can never be instantiated
• Defines a type
• Occupies a position in the class hierarchy
• Can be the parent of other classes, abstract or not.
• Has a unique parent which may or may not be abstract
• Has one or more constructors
• It can define abstract and non-abstract methods
• Can have instance fields (and often does have)

21
INTERFACES
• An Interface is a “promise of behaviour”
• It specifies the minimum functionality that a client requires of a supplier
• 100% abstract class
• can never be instantiated
• not a source of objects
• They are not really classes!
• They have no constructor
• They have no instance fields (only public static final fields – constants )
• Only abstract methods (as of Java 8 method implementation using default) is
allowed
• Note distinction between this and “interface to a system” and the interface(s)
of a class
22
ABSTRACT DATA TYPES
• An abstract data type (ADT) contains:
• data specific to a particular instantiation of the ADT
• methods to operate on those data
• The ADT is encapsulated, exposing just some of the subprograms
• Programs using the ADT can declare variables to contain an instance, called
an 'object', of the ADT

23
ABSTRACT DATA TYPE
• A countable number of items (in computing and in ordinary life)
• Conceptual, functional
• What, typically, would you want to do with a list?

I just want to keep a list of songs.


I want to add songs to the list.
I want to find out if a song is already on the list.
I want to delete a song from the list.
I want to sort the list.
• These common actions you would probably want to do on all lists!

24
IMPLEMENTATION
• Store the songs in an array?
Song[] musicList = new Song[200];

Song
songTitle Array contains references, not the songs
artistName
year

25
INTERFACE
• Use only insert(), find(), delete(),
sort() in client
• Hide user from array implementation, e.g. index
manipulation

26
IMPLEMENTATION
Class MusicList {
private Song[] playlist;
private int nElems;

public MusicList(int max) {


playlist = new Song[max];
nElems = 0;
}

public void insert(Song song)


{
playlist[nElems] = song;
nElems++;
}
}
27
CLIENT APPLICATION
class MusicPlayer {
public static void main(String[] args) {
int maxSize = 100;
MusicList list = new MusicList(maxSize);
Song bad = new Song("Bad", "U2", 1984);
Song purpleRain = new Song("Purple Rain","Prince",1984);
// insert 2 items:
list.insert(bad);
list.insert(purpleRain);
}
}

28
THE IMPLEMENTATION OF THE LIST IS HIDDEN
• An important idea in ADT development is to hide from the user some details of the
implementation:
THE NEED TO GROUP OBJECTS
• Many applications involve collections of objects:
• Personal organizers. (store events)
• Library catalogs (store books)
• Student-record systems (store students
• Characteristics of collections:
• The number of items to be stored is not usually fixed
• Need to be able to add items
• Need to be able to remove items
• You might be familiar with using arrays to group/store data
• arrays are very useful
• have strengths and weaknesses

30
HOW TO GROUP OBJECTS
• Perhaps sounds simple at first but consider what a useful collection must be able to do:
• Add something
• Insert
• append
• Remove something
• Remove from end
• Remove from middle
• Find an object in the collection (is it in the collection?)
• Retrieve it
• Count the number in a collection
• Allow duplicates?

31
JAVA COLLECTIONS API
• Java provides collection classes in the package java.util
• Interfaces, Abstract Classes and Concrete Classes
• All based on AbstractCollection which implements Collection
• collection classes offer a range of services (methods) for managing groups of
objects
• A good example of abstraction
• we write classes which are clients of collections
• our classes will use collection classes
• we are NOT concerned with how collection classes do what they do
• we are concerned with what they can do for us
• – does anyone know any of the Java Collection classes?
32
COLLECTION CLASS HIERARCHY

33
OVERVIEW OF SOME COLLECTION CLASSES
ArrayList Resizable array – grows in increments
Hashmap A collection of [key, data] pairs – order not guaranteed

HashSet Set implemented using a hash table – order not gtd


Hashtable A collection of [key, data] pairs – order not guaranteed

LinkedList A linked list


Stack Last In First Out (LIFO) data structure
TreeMap [key,data] pairs held in ascending order
TreeSet Set implemented as a tree
Vector Resizable array – synchronised access 34
ARRAYLIST – IMPLEMENTATION OF A LIST
• provides storage for an indexed collection of references to other objects
• allows the type of objects in the collection to be specified
• has constructor/s to create ArrayList objects for storing an unlimited number
of items (… object references)
• the index determines the position of object in the collection
• has methods (amongst others) to:
• add an item
• delete an item
• replace an item
• find an item given its index
• give the number of items in the collection

35
java.util.ArrayList<E>

Constructor for ArrayList (one of several)


ArrayList<E>()
Example ArrayList storing references to Strings
ArrayList<String> names = new ArrayList<String>()
Some methods in ArrayList class
boolean add (E element);
void add (int index, E element) ;
void set (int index, E element);
void remove (int index);
boolean remove (Object o);
E get (int index) ;
int size () ;
void clear ();

36
PARAMETERIZED ADTS – IN JAVA, GENERICS
• In statically typed languages, we have to define the type of things in
advance, e.g. what kind of object can go into an array
• In Java, generics provide the same facility and are a great help when
defining ADTs
• Generic programming
• briefly - programming style where functionality is written using a generic type
• where the type is going to be specified later
• In Java, a class be designed so that certain details can be added when it is going
to be used
• This allows for compile-time checking
37
ARRAYLIST WITHOUT GENERICS (PRE JAVA 1.5)
• In fact an ArrayList can hold any Object (the Java superclass) or subclass of
Object
• this is very flexible
• but when subclasses of Object are added to an ArrayList they are upcast to Object
• once retrieved they need to be downcast to be used
• This requires a lot of coding
• the compiler cannot check it – incorrect downcast causes a serious error

38
GENERIC TYPE IN JAVA
• Full class name for ArrayList
• java.util.ArrayList<E>
• Constructor for ArrayList (one of several) ArrayList<E>()
• Methods:
boolean add (E element);
E get (int index) ;

• The <E> indicates a sort of placeholder


• It must replaced with the class that is going to be stored in the ArrayList
• The compiler can then check whether in fact the correct class is being stored

39
WRITING YOUR OWN GENERIFIED TYPE
• Of course you can write a
class with a Generic type
• It needs to be stated in
the class declaration
and then can be used
throughout
• In this example type T
can be returned from
methods or passed as a
parameter to methods
40
ARRAYLIST METHODS

41
TRAVERSING THE ARRAYLIST
• Three options
1. The ArrayList has a method size() – returns the current size
1. Set up a loop and get each element in turn
2. You do not have to cast them (unless you know there is a subclass in
there) – see code example in arraylistdemo
2. The for each loop
1. Since Java 5
2. Syntax is as follows: for (ObjectTypeInCollection name :
collectionInstanceName) - see code example
3. Use an Iterator –
42
ITERATION for (String s : list) {
System.out.println(s);
• The for-each way is better
}
• Shorter
• Clearer
• Underlying implementation (array) does not have to be known

• If the underlying implementation changes (for instance, from String[] to


LinkedList<String>), the iteration code does not have to change!

• But how does this work?

43
ITERATION
• Design challenge. Support iteration over stack items by client,
without revealing the internal representation of the stack.

i N

s[]

first current

times of best the was it


null
• Java solution. Make stack implement the Iterable interface.
ITERATORS
• Q. What is an Iterable
?
• A. Has a method that public interface Iterable<Item> {
returns an Iterator. Iterator<Item> iterator();
}

public interface Iterator<Item> {


• Q. What is an Iterator boolean hasNext();
? Item next();
• A. Has methods void remove(); optional; use

hasNext() and next(). } at your own risk


ITERATORS
• Q. Why make data structures Iterable ?
• A. Java supports elegant client code.
“foreach” statement (shorthand)

for (String s : stack)


StdOut.println(s);

equivalent code (longhand)

Iterator<String> i = stack.iterator();
while (i.hasNext()) {
String s = i.next();
StdOut.println(s);
}
48
49
THE FUNDAMENTAL TRADE-OFF
• When consideration iteration:
• Time complexity: relation between number of elements and amount of time
• Memory complexity: relation between number of elements and amount of space
• Time and space trade-off
• Order of the complexity

• These are some of the fundamental topics we will cover during the course.

50
COLLECTIONS AND PRIMITIVE TYPES
• One limitation of Collections is that they cannot store primitive types
• For example HashMap holds [key, data] pairs
• Key cannot be a primitive type

• We must use a wrapper class


• Java has several classes which “wrap” primitive types
• Basically is object which holds a primitive type
• In java.lang so no import required

51
PRIMITIVE TYPE WRAPPERS
Integer int Can return int and has static utility methods
Boolean boolean Can return boolean
Character char
Byte byte Don’t get confused - class names should
always begin with capital
Float float Easy to get confused
Double double
Short short

52
EXAMPLE OF PRIMITIVE WRAPPER
• Primitive type:
• int primitiveInt = 1;
• Wrapper – use like any other class:
• Integer wrapperInt = new Integer( 1); (constructor
deprecated since Java 9 – see documentation)
• Can do this: primitiveInt = 3;
• Cannot do this (without autoxing – see next slide) : wrapperInt = 3;
• Integer is immutable
• To get the int value: primitiveInt = wrapperInt.intValue();
• You should not use Integer for scientific computing or performance sensitive
numerical code

53
AUTOBOXING
• This line of code will compile:
• list.add(12);
• where list is an instance of an ArrayList
• but int primitives cannot be added to an ArrayList directly?
• behind the scenes 12 is being put into an Integer which is being added to the ArrayList
• called autoboxing!
• Autoboxing also allows
Integer wrapperInt = 1;
wrapperInt = 3;

• Also auto unboxing:


• int i = list.get(0)
• where the element in the 0th position is an Integer

54
WRAPPER UTILITY METHODS
• The wrapper classes have a large number of static methods, for example:
• int count = Integer.parseInt(“15”);
• This is converting a String to an int – use with care….

• Java Documentation for Integer

55

You might also like