Sunteți pe pagina 1din 47

Session 4

OOP I
Agenda

OOP Introduction
Abstraction
Encapsulation
Composition
Inheritance
Polymorphism
Dynamic dispatch
Modularity (general topic)
OOP Introduction

Object Oriented Programming


Solving complex problems with functions (static methods)
is possible, but there are better methods

OOP - Object-oriented programming (OOP) is a


programming language model organized around objects
rather than "actions" and data rather than logic.
OOP Introduction

Solving complex problems with functions (static methods) is possible, but


there are better methods
We usually want to solve real problems about real entities around us:
Modeling a transportation system: trains, buses, cars, people, roads,
tolling,
Each entity has its own set of properties and operations: remember
the Data Type definition (set of values + operations)!
What if each entity would know how to do its operations and would hide
the details from us, just offering the operations we need?
We could then just make method calls on those entities, requesting them
to perform operations for us
OOP

Object - Any entity that has state


and behavior. For example: chair,
pen, table, keyboard, bike etc. It can
be physical and logical.
Class - is the blueprint from which
individual objects are created.
Abstraction

It is good to be able to simplify reality by defining classes which can


instantiate multiple objects of the problem; e.g. Car, Color, Particle. This
is called abstraction.
It denotes essential characteristics of an object that distinguishes it from
all other kinds of objects.
We establish a level of complexity, and suppress the more complex details
below the current level.
We define an abstraction called Car:
It can start, move, stop, change direction these are methods
Then, there are multiple types of cars: trucks, buses, motorcycles still,
the interface (API) remains the same, but we can have additional
properties and functionality
BUT these are added below the current level of complexity

Abstraction thus breaks complexity and helps me assign sub-problems


to classes.
Abstraction

An abstraction denotes essential characteristics of an


object that distinguishes it from all other kinds of
objects.
The object may have additional characteristics
Abstraction

Main car attributes / characteristics:


Fuel level
Gear
Speed
Color
Abstraction

Main car attributes / characteristics:


Fuel level
Gear
Speed
Color

class Car {
float fuelLevel;
byte gear;
float speed;
Color color;
}
Abstraction

Main car attributes / characteristics:


Fuel level
Gear
Speed
Color

class Car { // not perfect (well see later)


float fuelLevel;
byte gear;
float speed;
Color color;
}
Abstraction

Main car attributes / characteristics:


Fuel level
Gear
Speed
Color

class Car {
float fuelLevel; // these are class members
byte gear;
float speed;
Color color;
}
Abstraction

Abstraction is solved in Java via the class mechanism.


Whenever we identify a set of attributes and operations which can be
grouped, we should create a class for it:

class Person {
String name;
String surname;
byte age;

boolean hungry;

String toString() {
return name + + surname;
}
void eat() {
hungry = false;
}
}
Encapsulation

It is good to:
Be able to have entities which are made of data AND
behavior; they know how to handle their internal state.
Encapsulation

It is good to:
Be able to have entities which are made of data AND
behavior; they know how to handle their internal state.
Be able to hide unwanted details about how a certain class
solves its part of the problem.
Encapsulation

It is good to:
Be able to have entities which are made of data AND
behavior; they know how to handle their internal state.
Be able to hide unwanted details about how a certain class
solves its part of the problem.
The concept which allows both of these is called encapsulation.

E.g.: do we know how Integer.parseInt() does its job?


Encapsulation

It is good to:
Be able to have entities which are made of data AND
behavior; they know how to handle their internal state.
Be able to hide unwanted details about how a certain class
solves its part of the problem.
The concept which allows both of these is called encapsulation.

E.g.: do we know how Integer.parseInt() does its job?


Should we care?
Encapsulation

Groups the elements of an abstraction that constitute


its structure and behavior
Grouping is done in such a way that certain elements
are not accessible from outside => information hiding
Entities usually exhibit behavior and hide attributes
How behavior is implemented should not concern the
caller
This gives freedom to change the implementation
without affecting the clients.
Car operations:
Accelerate
Steer
ChangeGear
Brake
Encapsulation

class Car {
private float fuelLevel;
private byte gear;
private float speed;
private Color color;
}

We hide the internal attributes.


Encapsulation

class Car {
private float fuelLevel;
private byte gear;
private float speed;
private Color color;

public void accelerate(float speedDelta) {//}


public void steer(float angle) {//}
public void gearUp() {//}
public void gearDown() {//}
}
We hide internal attributes
We expose operations / behavior
These are visible from the outside
These operations will internally work with the private
attributes
Encapsulation

Encapsulation in Java is a
mechanism of wrapping the data
(variables) and code acting on the
data (methods) together as as
single unit.
In encapsulation the variables of a
class will be hidden from other
classes, and can be accessed only
through the methods of their
current class, therefore it is also
known as data hiding.
Activity

We create a public class called Light


Composition

A property which allows a type to be part of another


type (to be composed inside another object)
Remember - two main kind of types:
Primitive (built-in) types
Reference types: composed of primitive types and /
or other reference types
Also called has a / part of relationship. Two types:
Aggregation: weak composition; inner object not
destroyed when outer object is destroyed
Composition

A property which allows a type to be part of another


type (to be composed inside another object)
Remember - two main kind of types:
Primitive (built-in) types
Reference types: composed of primitive types and /
or other reference types
Also called has a / part of relationship. Two types:
Aggregation: weak composition; inner object not
destroyed when outer object is destroyed
Containment: strong composition; inner object is
destroyed when outer object is destroyed (window
is closed => buttons are destroyed)
Aggregation vs Composition
Inheritance

A property which allows a type to inherit the behavior


and structure of another type
Inheritance

A property which allows a type to inherit the behavior


and structure of another type
From generic to specific: specific data types exhibit the
same behavior as their (more generic) parents
Inheritance

A property which allows a type to inherit the behavior


and structure of another type
From generic to specific: specific data types exhibit the
same behavior as their (more generic) parents
e.g. Car and Bus, Car and Truck.
It makes no sense to re-implement the same behavior
in all possible specific classes.

the behavior is inherited.

There are means which allows us to implement a more


specific behavior
Inheritance
Composition vs Inheritance

Inheritance is known at compile-time and cannot


change at run-time.
Inheritance is a static property; we write in our code
that type B inherits from type A. Honda inherits from
Car.
Composition vs Inheritance

Inheritance is known at compile-time and cannot


change at run-time.
Inheritance is a static property; we write in our code
that type B inherits from type A. Honda inherits from
Car.
Composition is a dynamic property: we may not know
exactly which specific type is contained in our type until
the program executes.
Composition vs Inheritance

Inheritance is known at compile-time and cannot


change at run-time.
Inheritance is a static property; we write in our code
that type B inherits from type A. Honda inherits from
Car.
Composition is a dynamic property: we may not know
exactly which specific type is contained in our type until
the program executes.

e.g.: TreeTraverser is used to perform the same


operation on a certain tree-like node structure. We may
have several TreeTraversers: FindByIdTraverser,
LayoutTraverser, AxisAlignmentTraverser. Depending
on user action, one of them is called.
Polymorphism

Polymorphism is the ability of an object to take on many forms. The


most common use of polymorphism in OOP occurs when a parent
class reference is used to refer to a child class object.

When one task is performed by different ways i.e. known as


polymorphism. For example: to convense the customer differently, to
draw something e.g. shape or rectangle etc.

In JAVA, we use method overloading and method overriding to


achieve polymorphism.

Concept which allows treating the sub-classes in the


same way as treating the super-class.
Polymorphism

Concept which allows treating the sub-classes in the


same way as treating the super-class.

for (Shape shape : shapes) {


shape.draw();
}
Polymorphism

Concept which allows treating the sub-classes in the


same way as treating the super-class.

for (Shape shape : shapes) {


shape.draw();
}

shapes can contain circles, triangles, rectangles,


It is not known at compile-time what elements (sub-
types of Shape) shapes contains.
Polymorphism

Concept which allows treating the sub-classes in the


same way as treating the super-class.

for (Shape shape : shapes) {


shape.draw();
}

shapes can contain circles, triangles, rectangles,


It is not known at compile-time what elements (sub-
types of Shape) shapes contains.
the actual type of shape is not known at compile-
time. It can be any subclass (derived class) of Shape.
Polymorphism

Concept which allows treating the sub-classes in the


same way as treating the super-class.

for (Shape shape : shapes) {


shape.draw();
}

shapes can contain circles, triangles, rectangles,


It is not known at compile-time what elements (sub-
types of Shape) shapes contains.
the actual type of shape is not known at compile-
time. It can be any subclass (derived class) of Shape.
The declared type of shape is superclass (base class)
Shape.
Dynamic dispatch

shape.draw()

Does static compiler (javac) know which object


executes draw() at compile-time?
Dynamic dispatch

shape.draw()

Does static compiler (javac) know which object


executes draw() at compile-time?
javac doesnt know which draw() method to actually call
it only knows the declared type of shape (Shape).
The actual type of shape (Circle, Rectangle) will be
known when the program is executed (at run-time)
Dynamic dispatch

shape.draw()

Does static compiler (javac) know which object


executes draw() at compile-time?
javac doesnt know which draw() method to actually call
it only knows the declared type of shape (Shape).
The actual type of shape (Circle, Rectangle) will be
known when the program is executed (at run-time)
Only after the actual type is known, the JVM will call the
right method on the right object.
DD = The process of selecting the right implementation for a
polymorphic method.
Dynamic dispatch

shape.draw()

Does static compiler (javac) know which object


executes draw() at compile-time?
javac doesnt know which draw() method to actually call
it only knows the declared type of shape (Shape).
The actual type of shape (Circle, Rectangle) will be
known when the program is executed (at run-time)
Only after the actual type is known, the JVM will call the
right method on the right object.
DD = The process of selecting the right implementation for a
polymorphic method.

Calling a method on an object is called passing a message to


that object.
Dynamic dispatch

Java supports single dispatch: the right


implementation will be chosen only based on a single
type: the type of the instance on which the method is
called.
Dynamic dispatch

Java supports single dispatch: the right


implementation will be chosen only based on a single
type: the type of the instance on which the method is
called.
Low-level details:
JVM manages tables which map types (classes) to their
methods
Once the type is known, the right method is chosen from
the types table.
Open recursion

Object (non-static) methods can call other methods on


the same object.
This is possible by using the special variable called this.
The this variable is late-bound on the current object.
Modularity (general topic)

A quality of a system to be composed of a set of


cohesive, loosely coupled modules.
A module has a well-defined interface
A module interacts with other modules through
messages.
The message structure is well known.
Relevant for big applications. Wont stress too much
about it.
OOP Advantages

Discussion
What are the advantages of OOP?
Homework

Create a small application that mimics a library catalog. It needs to be


able to add books, delete books and list books. Books are of two kinds:
novels and art albums. They both have names and number of pages.
Novels have type (like mystery, sf, etc.) while albums have paper
quality.

Model these entities (book, novel, album) with different classes and
inheritance.
Bibliography

https://docs.oracle.com/javase/tutorial/java/co
ncepts/
Thinking in Java 1. Introduction To Objects
http://beginnersbook.com/2013/04/oops-
concepts/
http://www.tutorialspoint.com/java/java_abstra
ction.htm
http://www.tutorialspoint.com/java/java_encap
sulation.htm
http://www.tutorialspoint.com/java/java_inheri
tance.htm
http://www.tutorialspoint.com/java/java_overri
ding.htm

S-ar putea să vă placă și