java is an object-oriented language b in structured programming languages, methods define the...

34
Java is an Object-Oriented Java is an Object-Oriented Language Language In structured programming languages, methods In structured programming languages, methods define the structure of the programs, they are define the structure of the programs, they are basic building blocks basic building blocks Data has secondary role, it is just something that Data has secondary role, it is just something that is passed around. is passed around. In object oriented languages, the data has the In object oriented languages, the data has the principal role principal role Methods belong to the data, without the data, the Methods belong to the data, without the data, the method does not have any meaning (Except static method does not have any meaning (Except static methods) methods) Data and methods together make up the object. Data and methods together make up the object. OOP tries to model the real world. OOP tries to model the real world. What does the real world look like? What does the real world look like?

Post on 20-Dec-2015

231 views

Category:

Documents


0 download

TRANSCRIPT

Java is an Object-Oriented Java is an Object-Oriented LanguageLanguage

In structured programming languages, methods define the In structured programming languages, methods define the structure of the programs, they are basic building blocksstructure of the programs, they are basic building blocks

Data has secondary role, it is just something that is passed Data has secondary role, it is just something that is passed around.around.

In object oriented languages, the data has the principal roleIn object oriented languages, the data has the principal role Methods belong to the data, without the data, the method Methods belong to the data, without the data, the method

does not have any meaning (Except static methods)does not have any meaning (Except static methods) Data and methods together make up the object.Data and methods together make up the object. OOP tries to model the real world.OOP tries to model the real world. What does the real world look like?What does the real world look like?

Objects everywhere...Objects everywhere...

Real world entities

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

Red

Lying

Happy

Hooked

illBroken

Objects have behavior….Objects have behavior….

Hello, I am John

Nice to meet you

da da …

GrrrrrrrrVroemm

WorldWorld

The world is The world is • a set of thingsa set of things

• interacting with each other.interacting with each other.

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

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

Describing the worldDescribing the world

Describe a particular personDescribe a particular person• Ayse has long blond hair, green eyes, is 1.63m tall, weighs 56Kg and Ayse has long blond hair, green eyes, is 1.63m tall, weighs 56Kg and

studies computer engineering. Now lying down asleep.studies computer engineering. Now lying down asleep.

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

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

Object PropertiesObject Properties

IdentityIdentity StateState BehaviorBehavior

myLamp

onoff

Object is an abstraction of a real world entity

Introduction to ObjectsIntroduction to Objects

An An objectobject represents something with which we can interact represents something with which we can interact in a programin a program

An object provides a collection of services that we can tell it An object provides a collection of services that we can tell it to perform for usto perform for us

The services are defined by methods in a The services are defined by methods in a classclass that defines that defines the objectthe object

A class represents a concept, and an object represents the A class represents a concept, and an object represents the embodiment of a classembodiment of a class

A class can be used to create multiple objectsA class can be used to create multiple objects

Objects and ClassesObjects and Classes

Bank Account

A class(the concept)

John’s Bank AccountBalance: $5,257

An object(the realization)

Bill’s Bank AccountBalance: $1,245,069

Mary’s Bank AccountBalance: $16,833

Multiple objectsfrom the same class

Java OOP terminologyJava OOP terminology

ClassClass - Category - Category• Properties/statesProperties/states

• Functionality/ServicesFunctionality/Services(examines/alters state)(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.

Java OOP SoftwareJava OOP Software

Software SystemSoftware System• Set of objects Set of objects

• Which interact with each otherWhich 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

12

AbstractionAbstraction An An abstractionabstraction hides (or ignores) unnecessary details hides (or ignores) unnecessary details

denotes the essential properties of an objectdenotes the essential properties of an object One of the fundamental ways in which we handle One of the fundamental ways in which we handle

complexitycomplexity Objects are abstractions of real world entitiesObjects are abstractions of real world entities

Programming goal: choose the right abstractionsProgramming goal: choose the right abstractions

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

Multiple AbstractionsMultiple Abstractions

A single thing can have multiple abstractionsA single thing can have multiple abstractions

Example: a protein is…Example: a protein is… a sequence of amino acidsa sequence of amino acids a complicated 3D shape (a fold)a complicated 3D shape (a fold) a surface with “pockets” for ligandsa surface with “pockets” for ligands

Choosing AbstractionsChoosing Abstractions

Abstractions can be aboutAbstractions can be about tangible things (a vehicle, a car, a map) ortangible things (a vehicle, a car, a map) or intangible things (a meeting, a route, a schedule)intangible things (a meeting, a route, a schedule)

An example:An example: Abstraction name: lightAbstraction name: light Light’s wattage (i.e.,energy usage)Light’s wattage (i.e.,energy usage) Light can be on or offLight can be on or off

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

The essential properties are determined by the problemThe essential properties are determined by the problem

Object-Oriented ModelObject-Oriented Model

methods

data

Object boundary

Example: PencilExample: Pencil

location direction

penDown

home up down write

EncapsulationEncapsulation

the data belonging to an object is hidden, so variables are the data belonging to an object is hidden, so variables are privateprivate methods are methods are publicpublic we use the public methods to change or access the private datawe use the public methods to change or access the private data No dependence on implementationNo dependence on implementation

location direction

penDown

home up down writepublic

private

Programming ImplicationsProgramming Implications

Encapsulation makes programming easierEncapsulation makes programming easier• As long as the contract is the same, the client doesn’t care about the As long as the contract is the same, the client doesn’t care about the

implementationimplementation

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

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

Car ObjectsCar Objects

Defining class CarDefining class Car

What are the common attributes of cars?What are the common attributes of cars?

What are the common behaviors of cars?What are the common behaviors of cars?

Class Car Class Car

Car

colorspeedpower

driveturn rightturn left

stop

attributes

operations

class name

in Javain Java

Car

String colorint speedint power

drive()turnRight()turnLeft()

stop()

attributes or instance variables

methods

class name

Java SyntaxJava Syntax

public class Carpublic class Car{{// attribute declarations// attribute declarations

private String color;private String color;private int speed;private int speed;private int power;private int power;

// method declarations// method declarationspublic void drive()public void drive(){ // ….{ // ….}}

public void turnRight()public void turnRight(){ // ….{ // ….}}

public void turnLeft()public void turnLeft(){ // ….{ // ….}}

public void stop()public void stop(){ // ….{ // ….}}

}}

Car

String colorint speedint power

drive()turnRight()turnLeft()

stop()

Class PencilClass Pencil

Pencil

int locationString direction

home()up()

down()write()

attributes

methods

Name

Declaring objectsDeclaring objects

A class can be used to A class can be used to createcreate objects objects Objects are the instances of that classObjects are the instances of that class

Car

String colorint speedint power

drive()turnRight()turnLeft()

stop()

new

Java's "Building Blocks"Java's "Building Blocks"

Data types Data types • primitive constructs (e.g., integers, floating point numbers, primitive constructs (e.g., integers, floating point numbers,

characters)characters)

Class Class • A description of a set of objectsA description of a set of objects

• used to create objectsused to create objects

Primitive DataPrimitive Data

There are exactly eight primitive data types in JavaThere are exactly eight primitive data types in Java

Four of them represent integers:Four of them represent integers:• bytebyte, , shortshort, , intint, , longlong

Two of them represent floating point numbers:Two of them represent floating point numbers:• floatfloat, , doubledouble

One of them represents characters:One of them represents characters:• charchar

And one of them represents boolean values:And one of them represents boolean values:• booleanboolean

Declaring object variablesDeclaring object variables

A class name can be used as a type to declare an A class name can be used as a type to declare an object object reference variablereference variable

Person ayse;

An object reference variable holds the address of an objectAn object reference variable holds the address of an object

Declaring ObjectsDeclaring Objects

Person

String nameString birthDate

int age

getName()getAge

….

ClassPerson ayse;

ayse

is of Class

Creating ObjectsCreating Objects

We use the We use the newnew operator to create an operator to create an objectobject

ayse = new Person();

Creating an object is called Creating an object is called instantiationinstantiation

An object is an An object is an instanceinstance of a particular class of a particular class

We can combine declaration and creation:We can combine declaration and creation:

Person

String nameString birthDate

int age

getName()getAge

….

ayse

Class

Object

instance of

refers toPerson ayse = new Person();

is of Class

Declaring and Creating ObjectsDeclaring and Creating Objects

Flower

int ageint lengthint weight

getAge()getLength()

….

Class

karanfil = new Flower();

Object

instance of

refers to

Flower karanfil;

karanfil

is of Class

Basic approachBasic approach

Define classDefine class Declare objectsDeclare objects Create objectsCreate objects Use objectsUse objects

Using objectsUsing objects

• The way you work with objects is to send them messagesThe way you work with objects is to send them messages

• Most statements using objects have the following Most statements using objects have the following structurestructure

object.methodobject.method– for example: for example: thisPerson.setAge(24);thisPerson.setAge(24);

• This meansThis means– the object whose name is the object whose name is thisPersonthisPerson

– is sent the message is sent the message setAge()setAge()

– along with the "value" 24along with the "value" 24

• The effect of this is to set the person's age to be 24 years The effect of this is to set the person's age to be 24 years

oldold

ExampleExample

Person

String nameString birthDate

int age

setName(String name)setAge(int age)

getName()….

ayse

Class

Object

instance of

refers to

is of Class

ayse = new Person();

Person ayse;

ayse.setName(“Ayse Engin“);

Ayse Engin

ayse.setAge(24);

24