1 oop software usually tries to model real world problems what does the world look like?

40
1 OOP OOP Software usually tries to model real world problems What does the world look like?

Post on 21-Dec-2015

215 views

Category:

Documents


1 download

TRANSCRIPT

1

OOPOOP

Software usually tries to model real world problems

What does the world look like?

2

Objects everywhere...Objects everywhere...

Real world entities

3

WorldWorld

The world is • a set of things• interacting with each other.

OOP is more natural to humans, but less natural to computers

Computers (usually) have a single thread of control, so objects take turns

4

Describing the worldDescribing the world

Describe a particular person• Ayse has long blond hair, green eyes, is 1.63m tall,

weighs 56Kg and studies computer engineering. Now lying down asleep.

• Mehmet studies electronics, has short black hair and brown eyes. He is 180cm and 75 kilos. Now running to class!

Notice how all have specific values of• name, height, weight, eye colour, state, …

5

Objects have identity...Objects have identity...

Merhababen Ayse

My book

Dombo the elephant

Our house

The neighbour’s cat

Hasan’s computer

6

Objects have state...Objects have state...

Red

Lying

Happy

Hooked

illBroken

7

Objects have behavior….Objects have behavior….

Hello, I am John

Nice to meet you

da da …

GrrrrrrrrVroemm

8

Java OOP terminologyJava OOP terminology

Class - Category• Properties/states• Functionality/Services

(examines/alters state)

data

methods

object - Individual/unique thing(an instance of a class)

Particular value for each property/state & functionality of all members of class.

9

Java OOP SoftwareJava OOP Software

Software System• Set of objects • Which interact with each other

One object will send a message to another object asking it to do a particular task. The first object

does not need to know how the task is done (only how to request that it be done.)

This corresponds to calling one of the second object’s methods!

Created (instantiated) from class definitions

Person

Ayse David

“David”David: Say your name

10

In more detailIn more detail

Create & manipulate person objects

Name: “Ayse”Age: 18Salary: 500Comments:“Good student”

Name: “David”Age: 22Salary: 2000Comments:“Teaches CS101”

Personname, age,salary, commentssayName,getNetSalarygetCommentssetCommentsincreaseAge…

11

Coding Java ClassesCoding Java Classes

// header

public class Person {

// properties

// constructors

// methods

}

public void sayName() { System.out.println( name);

}

String name;int age;double salary;String comments;

public Person( String theName,int theAge ) {

name = theName;age = theAge;comments = “”;

}

12

Creating & Using ObjectsCreating & Using Objects

Always• Declare variable to “hold” object• Create object using “new” statement• Call object’s methods

“Ayse”name:

18age:

0.0salary:

“”

comments:

aStudent{Person}

Person aStudent;

aStudent = new Person( “Ayse”, 18);

aStudent.sayName();

Put this in method of another class,

(e.g main method)

13

Creating & Using ObjectsCreating & Using Objects

Person aStudent;aStudent = new Person( “Ayse”, 18);

Person friend;friend = new Person( “David”, 22);

“Ayse”name:

18age:

0.0salary:

“”

comments:

aStudent{Person}

“David”

name:

22age:

0.0salary:

“”

comments:

friend{Person}

friend.increaseAge();aStudent.setComments( “Good student”);

23

“Good student”

14

Data ScopeData Scope

The scope of data is the area in a program in which that data can be used (referenced)

Data declared at the class level can be used by all methods in that class

Data declared within a method can only be used in that method

Data declared within a method is called local data

Data and methods are primary components of a class, they work together to bring the concept alive as a unit

15

Local and Class scopeLocal and Class scope

public class X{private int a; // a has class scope, can be seen from

// anywhere inside the class ….public void m() {

a=5; // no problemint b = 0; // b is declared inside the method, local

scope…..} // here variable b is destroyed, no one will remember him

public void m2() {a=3; // okb = 4; // who is b? compiler will issue an error

}

16

Hotel room exampleHotel room example

public class X {int a;int b;

void m1 () {

System.out.println(a);m2();

}void m2() {

System.out.println(b);}

a=3b=4

o1

a=1b=2

o2

17

ParametersParameters

Each time a method is called, the actual arguments in the invocation are copied into the formal arguments

char calc (int num1, int num2, String message)

{ int sum = num1 + num2; char result = message.charAt (sum);

return result;}

ch = obj.calc (25, count, "Hello");

18

Parameters …Parameters … We can view the parameters as local variables given initial values when the

method gets called. Therefore they have local scope, valid only inside the method

char calc ()

{int num1 = 25;int num2 = count;String message = “Hello”;

int sum = num1 + num2; char result = message.charAt (sum);

return result;}

ch = obj.calc (25, count, "Hello");

19

Constructors RevisitedConstructors Revisited

Recall that a constructor is a special method that is used to set up a newly created object

When writing a constructor, remember that:• it has the same name as the class• it does not return a value• it has no return type, not even void• it often sets the initial values of instance variables

The programmer does not have to define a constructor for a class

20

Writing ClassesWriting Classes

Sometimes an object has to interact with other objects of the same type

For example, we might add two Rational number objects together as follows:

r3 = r1.add(r2);

One object (r1) is executing the method and another (r2) is passed as a parameter

See RationalNumbers.java (page 196) See Rational.java (page 197)

21

QuadraticPolynomialQuadraticPolynomial.java.javapublic class QuadraticPolynomial{

//instance variablesprivate double a;private double b ;private double c ;

// constructorpublic QuadraticPolynomial(double _a, double _b, double _c) {

a = _a;b = _b ;c = _c ;

}

//getter (Accessor) methodspublic double getA() {

return a ; }

 …

22

public double evaluate(double x) {

return a * x * x + b * x + c;}

public QuadraticPolynomial add(QuadraticPolynomial other){

return new QuadraticPolynomial(a + other.getA(), b + other.getB(), c + other.getC() );

// creates and returns a new polynomial which is is the derivative// of this polynomialpublic QuadraticPolynomial derivative(){

return new QuadraticPolynomial(0, 2 * a, b) ;

}

23

public boolean equals(QuadraticPolynomial other) {return (a == other.getA() && b == other.getB() && c == other.getC()); 

}

public double minValue(double start, double end, double delta){ double minValue = evaluate(start) ; double x = start + delta; while ( x <= end ) { double currValue = evaluate(x) ; if (currValue < minValue) minValue = currValue; x += delta ; } return minValue ;

}

24

QuadraticPolynomial qp1 = new QuadraticPolynomial(-1, -6, -5) ;QuadraticPolynomial qp2 = new QuadraticPolynomial(2, 2, 13) ;QuadraticPolynomial sum = qp1.add(qp2) ;

double minValue = sum.minValue(-4, 4, 0.05) ; System.out.println("The experimental minimum value is " + minValue);

QuadraticPolynomial sumd = sum.derivative() ; //find the value of x where the derivative equals to 0double extremePoint = -1 * sumd.getC() / sumd.getB() ; QuadraticPolynomial sumdd = sumd.derivative() ;

if ( sumdd.evaluate(extremePoint) <= 0) System.out.println("No minimum value");else System.out.println("The minimum value is " +

sum.evaluate(extremePoint));

25

26

Card1 codeCard1 code

public class Card1 {//constants for face valuesprivate static int ACE = 0;private static int JACK = 10;private static int QUEEN = 11;private static int KING = 12;

private static String ACE_ST = "Ace"; private static String JACK_ST = "Jack";private static String QUEEN_ST = "Queen";private static String KING_ST = "King";

// constants for suit valuesprivate static int CLUBS = 0; . . .

. . .private static String CLUBS_ST = "Clubs"; . . .

27

private int face; private int suit;

// creates a random cardpublic Card1 () {

face = (int) (Math.random () * 13);suit = (int) (Math.random () * 4);

}

public boolean isJack() {return face == JACK;

}

public boolean equals(Card1 other) {return face == other.face && suit == other.suit;

}

public boolean sameFace(Card1 other) {return face == other.face;

}

28

public int getScore() {return 1; // ??????????????????????????????????????

}

public String toString() {return getFaceName() + " of " + getSuitName();

}

private String getFaceName() {

if (face == ACE)return ACE_ST;

else if . . .

// must be something between 2 and 10return "" + (face + 1) ; // Integer.toString(face)

}

private String getSuitName() { . . . }

29

AbstractionAbstraction

An abstraction hides (or ignores) unnecessary details, denotes the essential properties of an object

Objects are abstractions of real world entities

Abstraction A car consists of four wheelsan engine, accumulator and brakes.

30

Card AbstractionCard Abstraction

A real world playing card has lots of properties like size, weight, color, texture, …

For our purposes, we decided which properties/behavior we really care about to play pisti, and ignored the rest

31

Multiple AbstractionsMultiple Abstractions

A single thing can have multiple abstractionsExample: a protein is… a sequence of amino acids a complicated 3D shape (a fold) a surface with “pockets” for ligands

32

Choosing AbstractionsChoosing Abstractions

Abstractions can be about tangible things (a vehicle, a car, a map) or intangible things (a meeting, a route, a schedule) An example: Abstraction name: light Light’s wattage (i.e.,energy usage) Light can be on or off

There are other possible properties (shape, color, socket size, etc.), but we have decided those are less essential

The essential properties are determined by the problem

33

Modeling Abstraction using Modeling Abstraction using ClassesClasses

A class defines all attributes/properties all behaviors/operationsof an abstractionIn Java… Attributes/properties correspond to fields (or variables) Behaviors/operations correspond to methods

class light {// Instance variablesprivate int wattage;private boolean on;// Instance methodspublic void switchOn ( ) { on = true; }public void switchOff ( ) { on = false; }public boolean isOn ( ) { return on; }public int getWattage ( ) { return wattage; }

}

34

EncapsulationEncapsulation

Encapsulation (information hiding)• No direct access to the parts of an object• No dependence on the object’s implementation

Classes support a particular kind of abstraction, encouraging separation

between an object’s operations and the implementations of those

operations This allows and encourages encapsulation Objects are regarded as “black boxes” whose internals are

hidden Separation of contract (i.e., what operations are available)

and implementation

35

Contract vs. ImplementationContract vs. Implementation

A class can be viewed as a contract; the contract specifies what operations are offered by the class• In Java, this corresponds to the method headings

for the methods that are public

A class can be viewed as an implementation; the implementation specifies how the desired behavior is produced• In Java, this corresponds to the method-bodies and

the (nonpublic) instance variables

36

Programming ImplicationsProgramming Implications

Encapsulation makes programming easier• As long as the contract is the same, the client

doesn’t care about the implementation

In Java, as long as the method signatures are the same, the implementation details can be changed• In other words, I can write my program using

simple implementations; then, if necessary, I can replace some of the simple implementations with efficient implementations

37

EncapsulationEncapsulation

An object should be self-governing

Any changes to the object's state (its variables) should be made only by that object's methods

We should make it difficult, if not impossible, to access an object’s variables other than via its methods

The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished

38

EncapsulationEncapsulation

An encapsulated object can be thought of as a black box

Its inner workings are hidden to the client, which invokes only the interface methods

Client Methods

Data

39

Another Card ImplementatioAnother Card Implementationnprivate String face;

private String suit;

// creates a random cardpublic Card2 () {

int faceCode = (int) (Math.random () * 13);face = getFaceName(faceCode);int suitCode = (int) (Math.random () * 4);suit = getSuitName(suitCode);

}

public boolean isJack() {return face.equals(JACK_ST);

}

public boolean equals(Card2 other) {return face.equals (other.face) && suit.equals ( other.suit);

}

public boolean sameFace(Card2 other) {return face.equals(other.face);

} . . …

40

PistiPisti