Transcript classes3

241-211 OOP (Java)
Semester 2, 2013-2014
3. Classes and Objects
• Objectives
– explain classes and objects
•
introduce fields, constructors, and methods
– go through two examples
241-211 OOP (Java): Classes/3
1
Topics
1. What are Classes, Objects?
2. The Contents of a Class
3. A Stack Class
4. Creating a Stack Object
5. Understanding a Stack Object
6. A Bad Stack Interface
7. Good vs. Bad Interfaces
8. Creating Two Stack Objects
9. Object Types vs. Primitive Types
10. A Ticket Machine
241-211 OOP (Java): Classes/3
2
1. What are Classes, Objects?
• A class is a factory for objects.
– e.g. a Car class is a factory for Car objects
• A Car class is not a Car object
– e.g. a Car factory is not the Cars it makes
Car
class
241-211 OOP (Java): Classes/3
Car objects
3
Very Important Slide
• A class consists of data (fields) and methods.
• Each object gets a copy of the class's data
(fields).
• An object uses the methods stored in the
class
– the class is a kind of method library for all of its
objects
241-211 OOP (Java): Classes/3
4
A Class Involves at least 2 People
• A class is implemented by one person.
• A class is used by other, different people.
• The implementor wants to make a class that is
easy to use.
• A user does not care how a class is
implemented. He only wants to know the
operations that it can carry out (its interface).
241-211 OOP (Java): Classes/3
5
A Class for a Stack
pop
push
Other operations:
is Empty
topOf
A Stack (of plates)
• This interface helps the implementor decide
on the class's operation/methods.
241-211 OOP (Java): Classes/3
6
2. The Contents of a Class
public class ClassName
{
Fields
// variables used by all methods
Constructor(s)
// method(s) that initialize an object
3 main parts
of a class
Methods (functions)
}
241-211 OOP (Java): Classes/3
7
Fields
•
Fields are the variables
(data) used by an
object.
•
Also known as
instance variables.
public class Stack
{
private int store[];
private int max_len;
private int top;
// all methods can use fields
}
visibility
type
variable name
private int top;
241-211 OOP (Java): Classes/3
8
Constructors
•
•
A constructor is a
special method which
initializes an object's
fields.
A constructor has the
same name as the
class.
241-211 OOP (Java): Classes/3
public Stack(int size)
{
store = new int[size];
max_len = size-1;
top = -1;
}
9
Methods
• Methods are functions very like C/C++
functions/methods.
• The methods that are visible to the user
(public) in a class depend on the interface of
the thing being implemented
– e.g. the stack interface → public methods
that a user can call
241-211 OOP (Java): Classes/3
10
3. A Stack Class
// Stack.java
// Written by the Stack implementor
public class Stack
{
private int store[];
private int max_len;
private int top;
public Stack(int size)
{ store = new int[size];
max_len = size-1;
top = -1;
}
:
241-211 OOP (Java): Classes/3
// hidden data
// visible method
continued
11
public boolean push(int number)
{
if (top == max_len)
return false;
top++;
store[top] = number;
return true;
}
:
241-211 OOP (Java): Classes/3
continued
12
public boolean pop()
{
if (top == -1)
return false;
top--;
return true;
}
public int topOf()
{ return store[top]; }
public boolean isEmpty()
{ return (top == -1); }
}
// end of Stack.java
241-211 OOP (Java): Classes/3
13
Stack Class Diagram
class name
fields
methods
constructor
'-' means private
'+' mean public
241-211 OOP (Java): Classes/3
14
4. Creating a Stack Object
// TestStack.java
// Written by the Stack user
import java.io.*;
public class TestStack {
public static void main(String args[])
{
Stack stk1 = new Stack(10);
hello object!!
stk1.push(42);
stk1.push(17);
stk1.pop();
System.out.println(“Top value is “ +
stk1.topOf() );
}
}
241-211 OOP (Java): Classes/3
15
Compilation and Execution
$ javac Stack.java
$ javac TestStack.java
$ java TestStack
Top value is 42
241-211 OOP (Java): Classes/3
Stack.class is in
the same directory as
TestStack.class.
16
Notes
• The user cannot directly access the object's
data (fields) because it is private.
• The user can call methods because they
are public
– the methods are the object's user interface
241-211 OOP (Java): Classes/3
continued
17
• Object creation:
Stack stk1 = new Stack(10)
has three parts:
Stack stk1
= new
Stack(10)
241-211 OOP (Java): Classes/3
// create a variable name, stk1
// create a Stack object
// call the constructor to
initialize the object state
18
Stack Object Diagram
Just after object creation:
stk1
0
store[]
max_len
9
top
-1
1 2
9
....
private means
the user of
the object
cannot directly
access the fields.
The stack object has a copy of the class' fields (data),
but uses the methods in the 'class library'.
241-211 OOP (Java): Classes/3
19
• Meaning of a method call:
– stk1.push(17) means call the push() method
stored in the Stack class, but apply it to the
stk1 object
• Methods work on an object's fields even
though the methods are stored in the class.
241-211 OOP (Java): Classes/3
20
Stack Object Diagram (later)
Just before the call to pop():
stk1
store[] 42 17
max_len
9
top
1
241-211 OOP (Java): Classes/3
....
21
5. Understanding a Stack Object
• What does the user need to understand in
order to use a Stack object?
• He only needs to understand the interface
– e.g.
push
pop
17
42
241-211 OOP (Java): Classes/3
is Empty
topOf
continued
22
• The user does not need to know how things
are implemented
– the user is happy since the interface is simple
– the implementor is happy since he can change
the implementation (e.g. make it faster), and the
user will not complain (so long as the interface
does not change)
241-211 OOP (Java): Classes/3
23
6. A Bad Stack Interface
// BadStack.java
// Written by the ฺBadStack implementor
public class BadStack
{
private int store[];
private int max_len;
public int top;
// constructor and methods same as in Stack
:
241-211 OOP (Java): Classes/3
24
Creating a BadStack Object
// TestBadStack.java
// Written by the BadStack user
import java.io.*;
public class TestBadStack {
public static void main(String args[])
{
BadStack stk1 = new BadStack(10);
hello object!!
stk1.push(42);
stk1.push(17);
stk1.top = 0;
stk1.pop();
System.out.println(“Top value is “ +
stk1.topOf() );
}
} OOP (Java): Classes/3
241-211
?
25
Understanding the BadStack Object
• What does the user need to understand in
order to use the BadStack object?
• He needs to understand the interface and
implementation
push
pop
– e.g.
17
42
241-211 OOP (Java): Classes/3
+ store[], top,
max_len
26
7. Good vs Bad Interfaces
• A good interface hides the class's
implementation
– all fields are private
• A good interface can be visualized by the
user (e.g the stack diagram)
• A good interface has easy-to-understand
public methods.
241-211 OOP (Java): Classes/3
27
Kinds of Methods in an Interface
• Aside from the constructor, most public
methods can be grouped into two types:
– accessor (get) methods
•
•
they return information to
the user
e.g. in Stack: isEmpty(), topOf()
– mutator (set) methods
•
•
they change the object's state (its fields)
e.g. in Stack: push(), pop()
241-211 OOP (Java): Classes/3
28
An Accessor (Get) Method
return type
visibility modifier
method name
public int topOf()
{
return store[top];
}
parameter list
(usually empty)
return statement
start and end of method body (block)
241-211 OOP (Java): Classes/3
29
A Mutator (Set) Method
visibility modifier
return type
method name
parameter(s)
public boolean push(int number)
{
if (top == max_len)
return false;
top++;
store[top] = number; fields being mutated
return true;
}
241-211 OOP (Java): Classes/3
30
8. Creating Two Stack Objects
• Many objects can be created from a class:
:
// in main() of TestStack
Stack stk1 = new Stack(10);
Stack stk2 = new Stack(20);
stk1.push(27);
stk1.push(13);
stk2.push(10);
el = stk2.topOf();
:
241-211 OOP (Java): Classes/3
create two
objects
31
Stack Objects Diagrams
stk1
store[] 27 13
max_len
8
top
1
....
Just before the
call to topOf():
stk2
store[] 10
max_len
top
241-211 OOP (Java): Classes/3
....
19
0
32
Notes
• The two objects have two copies of the
class's data
– changes in one object do not affect the other
object
• Both objects use the methods in the class
– stk1.push(13) means call push() and apply
it to the data inside stk1
241-211 OOP (Java): Classes/3
33
9. Object Types vs. Primitive Types
Foo object
a
Foo a = new Foo();
object type
int i;
i = 32;
32
primitive type
i
Primitive types include:
int, float, double, char, byte
241-211 OOP (Java): Classes/3
34
Assignment Differences
Foo a = new Foo();
Foo b;
b = a;
a
b
copy the link
(the reference)
Foo object
32
a
241-211 OOP (Java): Classes/3
int a = 32;
int b;
b = a;
copy the value
32
b
35
10. A Ticket Machine
show price
(and other info)
print
ticket
show balance
(the amount
of money
entered)
insert money
give change
• The required interface helps the implementor
decide on the class’s methods.
241-211 OOP (Java): Classes/3
36
10.1. Class Diagram
accessor
methods
mutator method
constructor
241-211 OOP (Java): Classes/3
accessor/
mutator
methods
(tricky to
understand)
37
10.2 Ticket Machine Class
public class TicketMachine
{
private int price;
// price of a ticket
private int balance; // amount entered by customer
private int total;
// total money in machine
public TicketMachine(int ticketCost)
{ price = ticketCost; // set the ticket price
balance = 0;
total = 0;
}
241-211 OOP (Java): Classes/3
continued
38
public int getPrice()
{ return price; }
public int getBalance()
{ return balance; }
public int getTotal()
{ return total; }
241-211 OOP (Java): Classes/3
continued
39
public void insertMoney(int amount)
// process money inserted into the machine
{
if (amount > 0)
balance = balance + amount;
else
System.out.println("Use a positive amount: "
+ amount);
}
241-211 OOP (Java): Classes/3
continued
40
public void printTicket()
{ if (balance >= price) {// if enough money inserted
// Simulate the printing of a ticket.
System.out.println("##################");
System.out.println("# Ticket");
System.out.println("# " + price + " baht.");
System.out.println("##################");
System.out.println();
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the prince.
balance = balance - price;
}
else
// report error
System.out.println(
"You must insert at least: " +
(price - balance) + " more baht.");
} // end of printTicket()
241-211 OOP (Java): Classes/3
continued
41
public int refundBalance()
{
int amountToRefund;
amountToRefund = balance;
balance = 0;
//clear ticket machine's balance
return amountToRefund;
//return balance amount
}
}
// end of TicketMachine class
241-211 OOP (Java): Classes/3
42
10.3. Local Variables
• Fields are one sort of variable
– they store values through the life of an object
– they are accessible by all the methods
• Methods can include shorter-lived variables:
– they exist only as long as the method is being executed
– they are only accessible from within the method
241-211 OOP (Java): Classes/3
43
Local Variable Example
A local variable
No visibility
modifier
241-211 OOP (Java): Classes/3
public int refundBalance()
{
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
44
10.4. Using a TicketMachine Object
public class TMDemo
{
public static void main(String[] args)
{
TicketMachine tm = new TicketMachine(10);
// tickets cost 10
System.out.println("Ticket price: "
+ tm.getPrice());
System.out.println("Current total: "
+ tm.getTotal());
System.out.println("Insert 5 baht");
tm.insertMoney(5);
:
241-211 OOP (Java): Classes/3
45
System.out.println("Insert 10 baht");
tm.insertMoney(10);
System.out.println("Current balance: " +
tm.getBalance());
tm.printTicket();
System.out.println("Current balance: " +
tm.getBalance());
System.out.println("Current total: " +
tm.getTotal());
:
241-211 OOP (Java): Classes/3
46
System.out.println("Request Change");
System.out.println("Change is: " +
tm.refundBalance());
System.out.println("Current balance: " +
tm.getBalance());
} // end of main()
} // end of TMDemo class
241-211 OOP (Java): Classes/3
47
Compilation
$ javac TicketMachine.java
$ javac TMDemo.java
TicketMachine.class is in
the same directory as
TMDemo.class.
241-211 OOP (Java): Classes/3
48
Output of
java TMDemo
Ticket price: 10
Current total: 0
Insert 5 baht
Insert 10 baht
Current balance: 15
##################
# Ticket
# 10 baht.
##################
Current balance: 5
Current total: 10
Request Change
Change is: 5
Current balance: 0
241-211 OOP (Java): Classes/3
49
TicketMachine Object Diagram
Just after object creation:
tm
price
balance
total
10
0
0
The TicketMachine object has a copy of the class' data,
but uses the methods in the 'class library'.
241-211 OOP (Java): Classes/3
50