Transcript object
OOP
Software usually tries to model real world problems
What does the world look like?
1
Objects everywhere...
Real world entities
2
World
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
3
Describing 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, …
4
Objects have identity...
Merhaba
ben Ayse
My book
Dombo the elephant
Our house
The neighbour’s cat
Hasan’s computer
5
Objects have state...
Lying
Red
Hooked
Broken
Happy
ill
6
Objects have behavior….
Hello,
I am John
da da
…
Nice to
meet you
Grrrrrrrr
Vroemm
7
Java 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.
8
Java OOP Software
Software System
• Set of objects
• Which interact with each other
Created (instantiated)
from class definitions
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!
Person
Ayse
David: Say your name
David
“David”
9
In more detail
Create & manipulate person objects
Person
name,
age,
salary,
comments
sayName,
getNetSalary
getComments
setComments
increaseAge
…
Name: “Ayse”
Age: 18
Salary: 500
Comments:
“Good student”
Name: “David”
Age: 22
Salary: 2000
Comments:
“Teaches CS101”
10
Coding Java Classes
// header
public class Person {
// properties
// constructors
// methods
}
String
int
double
String
name;
age;
salary;
comments;
public Person( String theName,
int
theAge ) {
name = theName;
age = theAge;
comments = “”;
}
public void sayName() {
System.out.println( name);
}
11
Creating & Using Objects
Always
• Declare variable to “hold” object
• Create object using “new” statement
• Call object’s methods
Person aStudent;
aStudent = new Person( “Ayse”, 18);
aStudent.sayName();
Put this in method
of another class,
(e.g main
method)
name:
aStudent
{Person}
“Ayse”
age:
18
salary:
0.0
comments:
“”
12
Creating & Using Objects
Person aStudent;
aStudent = new Person( “Ayse”, 18);
Person friend;
friend = new Person( “David”, 22);
name:
aStudent
{Person}
“Ayse”
age:
18
salary:
0.0
name:
friend
{Person}
comments:
“Good “”
student”
friend.increaseAge();
aStudent.setComments( “Good student”);
“David”
age:
22
23
salary:
0.0
comments:
“”
13
Data 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
14
Local 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 problem
int 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; // ok
b = 4; // who is b? compiler will issue an error
}
15
Hotel room example
public class X {
int a;
int b;
void m1 () {
System.out.println(a);
m2();
}
void m2() {
System.out.println(b);
}
o1
a=3
b=4
o2
a=1
b=2
16
Parameters
Each time a method is called, the actual arguments in the invocation
are copied into the formal arguments
ch = obj.calc (25, count, "Hello");
char calc (int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt (sum);
return result;
}
17
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
ch = obj.calc (25, count, "Hello");
char calc ()
{
int num1 = 25;
int num2 = count;
String message = “Hello”;
int sum = num1 + num2;
char result = message.charAt (sum);
return result;
18
Constructors 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
19
Writing 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)
20
QuadraticPolynomial.java
public class QuadraticPolynomial
{
//instance variables
private double a;
private double b ;
private double c ;
// constructor
public QuadraticPolynomial(double _a, double _b, double _c) {
a = _a;
b = _b
;
c = _c
;
}
//getter (Accessor) methods
public double getA() {
return a
;
}
…
21
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 polynomial
public QuadraticPolynomial derivative()
{
return new QuadraticPolynomial(0, 2 * a, b)
;
}
22
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
}
;
23
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 0
double 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
sum.evaluate(extremePoint));
;
;
is
"
+
24
25
Card1 code
public class Card1 {
//constants for face values
private 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 values
private static int CLUBS = 0; . . .
...
private static String CLUBS_ST = "Clubs"; . . .
26
private int face;
private int suit;
// creates a random card
public 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;
}
27
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 10
return "" + (face + 1) ; // Integer.toString(face)
}
private String getSuitName() { . . . }
28
Abstraction
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 wheels
an engine, accumulator
and brakes.
29
Card 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
30
Multiple Abstractions
A single thing can have multiple abstractions
Example: a protein is…
a sequence of amino acids
a complicated 3D shape (a fold)
a surface with “pockets” for ligands
31
Choosing 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
32
Modeling Abstraction using Classes
A class defines
all attributes/properties
all behaviors/operations
of an abstraction
In Java…
Attributes/properties correspond to fields (or variables)
Behaviors/operations correspond to methods
class light {
// Instance variables
private int wattage;
private boolean on;
// Instance methods
public void switchOn ( ) { on = true; }
public void switchOff ( ) { on = false; }
public boolean isOn ( ) { return on; }
public int getWattage ( ) { return wattage; }
}
33
Encapsulation
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
34
Contract 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
35
Programming 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
36
Encapsulation
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
37
Encapsulation
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
38
Another Card Implementation
private String face;
private String suit;
// creates a random card
public 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);
} . . …
39
Pisti
40