ch08
ch08
OBJECTS AND
CLASSES
Objects and Programs
Java programs are made of objects that interact
with each other
Each object is based on a class
A class describes a set of objects with the same
behavior
Each class defines a specific set of methods to
use with its objects
For example, the String class provides methods:
• Examples: length() and charAt() methods
String greeting = “Hello World”;
int len = greeting.length();
char c1 = greeting.charAt(0);
Diagram of a Class
Private Data Class
Each object has its own private Private Data
data that other objects cannot (Variables)
directly access
Methods of the public interface
provide access to private data, Public Interface
while hiding implementation (Methods)
details:
This is called Encapsulation
Public Interface
Each object has a set of
methods available for other
objects to use
8.2 Implementing a Simple Class
Example: Tally Counter: A class that models
a mechanical device that is used to count people
For example, to find out how many people attend a
concert or board a bus
What should it do?
Increment the tally
Get the current total
Tally Counter Class
Specify instance variables in the class
declaration:
variables
Keeping a Total
Counting Events
Collecting Values
Managing Object Properties
Modeling Objects with Distinct States
Describing the Position of an Object
Patterns: Keeping a Total
Examples public class CashRegister
{
Bank account balance
private double totalPrice;
Cash Register total
Car gas tank fuel level public void addItem(double price)
{
Variables needed totalPrice += price;
}
Total (totalPrice) public void clear()
Methods Required {
totalPrice = 0;
Add (addItem) }
Clear public double getTotal()
{
getTotal return totalPrice;
}
}
Patterns: Counting Events
public class CashRegister
Examples {
Cash Register items private double totalPrice;
private int itemCount;
Bank transaction fee public void addItem(double price)
Variables needed {
totalPrice += price;
Count itemCount++;
}
Methods Required public void clear()
Add {
totalPrice = 0;
Clear itemCount = 0;
Optional: getCount }
public double getCount()
{
return itemCount;
}
}
Patterns: Collecting Values
public class Cart
Examples {
Multiple choice private String[] items;
private int itemCount;
question public Cart() // Constructor
Shopping cart {
items = new String[50];
Storing values itemCount = 0;
Array or ArrayList }
public void addItem(String name)
Constructor {
Initialize to empty if(itemCount < 50)
{
collection items[itemCount] = name;
Methods Required itemCount++;
}
Add }
}
Patterns: Managing Properties
public class Student
A property of an object {
can be set and private String name;
private int ID;
retrieved public Student(int anID)
{
Examples
ID = anID;
Student: name, ID }
public void setName(String newname)
Constructor {
Set a unique value if (newName.length() > 0)
name = newName;
Methods Required }
set public getName()
{
get return name;
}
}
Patterns: Modeling Stateful Objects
public class Fish
Some objects can be in one {
of a set of distinct states. private int hungry;
public static final int
Example: A fish NOT_HUNGRY = 0;
public static final int
Hunger states: SOMEWHAT_HUNGRY = 1;
• Somewhat Hungry public static final int
• Very Hungry VERY_HUNGRY = 2;
• Not Hungry
public void eat()
Methods will change the {
hungry = NOT_HUNGRY;
state }
eat public void move()
{
move if (hungry < VERY_HUNGRY)
{ hungry++; }
}
Patterns: Object Position
Examples public class Bug
{
Game object private int row;
Bug (on a grid) private int column;
private int direction;
Cannonball // 0 = N, 1 = E, 2 = S, 3 = W
Storing values public void moveOneUnit()
{
Row, column, direction, switch(direction) {
speed. . . case 0: row--; break;
case 1: column++; break;
Methods Required . . .
move }
}
turn }
8.10 Object References
Objects are similar to arrays because they always
have reference variables
Array Reference
Object Reference
Shared References
CashRegister reg2 = reg1;
if (middleInitial == null)
System.out.println(firstName + " " + lastName);
else
System.out.println(firstName + " " + middleInitial + ". "
+ lastName);
The this reference
Methods receive the ‘implicit parameter’ in a
reference variable called ‘this’
It is a reference to the object the method was
invoked on:
public BankAccount()
{
lastAssignedNumber++;
accountNumber = lastAssignedNumber;
}
. . . Methods of any object of the class can use
} or change the value of a static variable
Using Static Variables
Example:
Each time a new account is created,
the lastAssignedNumber variable is
incremented by the constructor
Access the static variable using:
ClassName.variableName
Using Static Methods