Oo 1

You might also like

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

MODULE: Abstractions

Decomposition
Abstraction types
Specifications
Contract
Mutability
Invariants
Operation types
Encapsulation

javaprogrammering
Decomposition
Complex problem Strategy: ”Divide and conquer!”

• Divide into smaller problems and solve each one


independently

• Combine the solutions to solve the complex problem


(integration)

• Abstract decompose abstract decompose …

javaprogrammering
Hotel
hotel
floor
room
facilities
document
reservation
receipt
person
guest
personnel
clerk
cleaning staff
chef

javaprogrammering
Abstraction
• Abstract – “to consider apart from application to a
particular instance” (Webster’s Dictionary)

• Abstrahera – ”skapa en allmän och övergripande


föreställning (om ngt) genom att bortse från detaljer”
(Nationalencyclopedin)

javaprogrammering
General abstraction types
• Abstraction by parameterization – abstract from specific
identifiers to parameters; allows for general use (reuse) (cf.
actual vs formal parameters)

• Abstraction by specification – abstract from specific


implementation to general behaviour

javaprogrammering
Abstraction types
• Procedural abstractions (functional abstractions) –
operations, e g sort(), sqrt(), abs()

• Data abstractions – classes or interfaces, e g Customer,


Shape, Vehicle

• Iteration abstractions – e g Enumeration and


Iterator in Java

javaprogrammering
Why abstractions?
• Easy to understand – you only need to understand what a
method does, not how it does it

• Facilitates teamwork, distribution of labour

• Facilitates modification and maintenance

javaprogrammering
Procedural abstraction, ex 1
Repeated code; different identifiers but same function:

if (a<0) a=(-a);
.
.
if (varB<0) varB=(-varB);
.
.
if (anotherVar<0) anotherVar=(-anotherVar);
.

javaprogrammering
Procedural abstraction, ex 1 (cont)
/** Returns the absolute value of p */
public static int abs(int p) {
int i=p;
if (i<0) {
i=(-i);
}
return i;
}

javaprogrammering
Procedural abstraction, ex 1 (cont)
a = abs(a);
.
.
varB = abs(varB);
.
.
anotherVar = abs(anotherVar);
.

javaprogrammering
Procedural abstraction, ex 1 (cont)
Abstraction by
specification

/** Returns the absolute value of p */


public static int abs(int p) {
int i=p;
if (i<0) {
i=(-i); Abstraction by
parameterization
}
return i; (Implementation
} not relevant…)

javaprogrammering
Procedural abstraction, ex 2
Abstraction by
specification

/** Sorts an int-array in descending order.


If iArr is null a NullPointerException is
thrown. Returns a reference to the sorted
array. */
public static int[] sort(int[] iArr){ … }

Abstraction by
parameterization

javaprogrammering
Contract
Contract – often used to describe procedural
abstractions (but also e g interfaces).

• ”If you provide …, then I promise to …”

• Pre-conditions

• Post-conditions

javaprogrammering
Specifications for procedures
• Description of abstraction
• Can contain:
– What is required? (e.g. non-null input)
– What is returned? (if any…)
– What is modified? (any inputs changed?)
– What is the behaviour? (assuming requirements are
satisfied)
• Usually informal
• Use javadoc (comment before method definition)

javaprogrammering
Specifications for procedures
• Too specific constrains the implementor (e.g. an id-
number must comply with a certain format)

• Too general limits the usefulness (to have wheels is not


sufficient in order to be a useful abstraction for Vehicle)

javaprogrammering
Data abstraction
• Fundamental in OO-programming!

• Data abstraction = type, with data and operations

• Expressed in the form of a set of public operations (data


are available through the operations)

• Inner representation of data is not relevant

• Corresponds to class and interface in Java

javaprogrammering
Abstraction function, class invariant
• Abstraction function (AF) – formal description of the
relationship between an abstraction and the (typical)
internal representation of its implementation

• Class invariant (CI, also “representation invariant”) –


description of class-scope requirements (e.g. balance must
always be kept updated for an Account, size of a set must
never be greater than the number of set-members, etc.)

• In practice, AF and CI are rarely used formally (invariants


may be checked as part of contracts [using assert()], and
documented as attribute comments etc.)

javaprogrammering
Specifications for data abstractions
• Conceptual description

• Description of area of responsibility

• Mutable or immutable?

• Public interface (public operations)

• Use javadoc (comment before class definition)

javaprogrammering
Specification, class Person
/** This class represents a person with name, address and an id-number.
All but the id-number can be modified through the provided set-
methods.*/
public class Person {
/** The id is unique and cannot be changed. */
private int id;
.
.
/** Sets the name of this person. If the provided string is non-valid (null
or empty) a NonValidNameException will be thrown. */
public void setName(String s) throws NonValidNameException {

}
.
}
javaprogrammering
Operation types
• Creators – produces new objects “from scratch” (most
constructors)

• Producers – produces new objects from object of same


type (e.g. copy-methods)

• Mutators – modifies data, only mutable types (e.g. set-


methods)

• Observers – returns information (e.g. get-methods)

javaprogrammering
public class Person{
class Person, ex
private String name;
private String addr;
private String id;
public Person(String n, String a, String i) {
name = n;
addr = a;
id = i; constructor
} observer
public String getName(){
return name; mutator
}
public void setName(String n) throws NonValidNameException{
if (n!=null && n.length()>0) name = n;
else throw new NonValidNameException();
}
producer
public Person createChild(String n, String i) {

}
.
. javaprogrammering
Mutability
• Mutable – data can be changed

• Immutable – data cannot be changed (data are private,


there are no mutators)

• Many standard library classes are immutable, e g String,


Integer, Character, etc

• What happens here?


String s1 = “ABC”;
s1 = s1 + “DEF”;

javaprogrammering
Mutable or immutable?
• Would the object naturally have changing values?

• Immutable is safer

• Mutable is more flexible and effective

• Immutable: e.g. Integer, String, Shape, Amount etc.

• Mutable: e.g. Account, MembershipRecord, Customer etc.

javaprogrammering
public class Employee{
Encapsulation, ex
private int salary;
public Employee(int s) { salary = s; }
public setSalary(int s) throws NonValidSalaryException {
if(s>0 && s <= 40000){
salary = s;
} else throw new NonValidSalaryException();
}
}

.
.
Employee e = new Empoyee(20000);
e.salary = -10000; // not allowed! (compile error)
e.setSalary(-10000); // will throw exception (at runtime)
e.setSalary(10000); // works!
.
.

javaprogrammering
Encapsulation
Make the data unreachable from outside – access only via
public methods (a public interface).

• Supports data abstraction (data representation separated


from public API)

• Required for immutable objects

• Protects data from direct access

• Breaking the encapsulation is also referred to as “exposing


the rep[resentation]” (e.g. Liskov & Guttag)

javaprogrammering
Exposing the representation
public MyArrayContainer {
private int[] iArr;
public MyArrayContainer(int[] a) {
iArr = a;
}
public int getElement(int indx) {
return iArr[indx];
}
public int[] getAllElements() {
return iArr;
} One constructor and two
} observers, but no mutators…
- Is it immutable?
javaprogrammering
How many operations?
• A “fully populated” type has operations sufficient to obtain
every possible state.

• What is the type’s area of responsibility?

• “Identify everything users might reasonably expect to do


[and implement the operations necessary]” (Is this really
always a good strategy?)

javaprogrammering
MODULE: Inheritance
• Polymorphism
• Access modifiers
• Casting
• Constructors
• Overriding
• this and super
• Interface
• static

javaprogrammering
Abstraction hierarchy
Person

Customer Employee

CEO Secretary Sales person

javaprogrammering
class Person{
Inheritance, ex
String name;
String addr;
}

class Customer extends Person{


String custNo;
}

class Personnel extends Person{


int salary;
}

class SalesPerson extends Personnel{


int bonus;
}

javaprogrammering
class Car{
String regNo;
Vehicle, ex
int fuelConsumption;
int maxLoad;
int noOfPassengers;
}

class Motorcycle{
String regNo;
int fuelConsumption;
int noOfPassengers;
}

class Aeroplane{
int fuelConsumption;
int maxLoad;
int noOfPassengers;
}

javaprogrammering
class Vehicle{
Vehicle, ex (cont)
int fuelConsumption;
int maxLoad;
int noOfPassengers;
}

class RegisterableVehicle extends Vehicle{


String regNo;
}

class Car extends RegisterableVehicle {


}

class Motorcycle extends RegisterableVehicle {


}

class Aeroplane extends Vehicle {


}

javaprogrammering
”Is-a” relation
Vehicle
fuelConsumption:int
maxLoad:int
noOfPassengers:int

RegisterableVehicle
Aeroplane regNo:String

Motorcycle Car

javaprogrammering
Heterogeneous collections
public class HeterogeneousCollection {

public static void main(String [] args){

Vehicle[] myVehicles = {
new Car(),
new Motorcycle(),
new Aeroplane() };

for(int i = 0;i< myVehicles.length; i++){


System.out.println(”Max. load: ” +
myVehicles[i].maxLoad);
}
}
}
javaprogrammering
Instanceof and downcast
public class HeterogeneousCollection {

public static void main(String [] args){


Vehicle[] myVehicles = {new Car(),
new Motorcycle(), new Aeroplane() };
for(int i = 0; i<myVehicles.length; i++){
Vehicle v = myVehicles [i];
System.out.println(v.fuelConsumption);
System.out.println(v.maxLoad);
System.out.println(v.noOfPassengers);
if(v instanceof RegisterableVehicle){
RegisterableVehicle rv = (RegisterableVehicle) v;
System.out.println(rv.regNo);
}
} // end for
} // end main()

}
javaprogrammering
This document was created with Win2PDF available at http://www.daneprairie.com.
The unregistered version of Win2PDF is for evaluation or non-commercial use only.

You might also like