Readings
Objects and Classes - Introduction
Chapter 4 focuses on:
Objects
An object has:
Classes
A class is a blueprint of an object
It is the model or pattern from which objects are created
A class defines the methods and types of data associated with an object
Creating an object from a class is called
instantiation; an object is an instance of a particular class
For example, the Account class could
describe many bank accounts, but toms_savings is a particular
bank account with a particular balance
Creating Objects
The new operator creates an object from a class:
Account toms_savings = new Account ();ClassName identifier = new ClassName(ParameterList);
This declaration asserts that toms_savings is a variable that refers to an object created from the Account class
It is initialized to the object created by the new operator
The newly created object is set up by a call to a constructor of the
class
Constructors
A constructor is a special method used to set up an object
It has the same name as the class
It can take parameters, which are often used to initialize some variables in the object
For example, the Account constructor could be set up to take a parameter specifying its initial balance:
Account toms_savings = new Account (125.89);
Object References
The declaration of the object reference
variable and the creation of the object can
be separate activities:
Account toms_savings; toms_savings = new Account (125.89);Once an object exists, its methods can be invoked using the dot operator:
toms_savings.deposit (35.00);
The String Class
A character string in Java is an object, defined by the String class
String name = new String ("Ken Arnold");
String name = "Ken Arnold"; // abbreviated syntax
Java strings are immutable; once a string
A character in a string can be referred to by its position, or index starting at zero - charAt method.
The String class is in java.lang
The StringTokenizer Class
The StringTokenizer class makes it easy to break up a string into pieces called tokens
By default, the delimiters for the tokens are the space, tab, carriage return, and newline characters (white space)
The StringTokenizer class is defined in the java.util package.
See Int_Reader.java
The Random Class
The Random class provides methods to
simulate a random number generator
The nextInt method returns a random integer from all int values.
Usually, the integer must be scaled and
shifted into a particular range
Expression Range Math.abs (rand.newInt()) % 10 + 1 1 to 10 Math.abs (rand.newInt()) % 101 0 to 100 Math.abs (rand.newInt()) % 11 + 20 20 to 30 Math.abs (rand.newInt()) % 11 - 5 -5 to 5
Assignment
Primitive data type declaration and
assignment
int x; // declaration: TYPE IDENTIFIER; x = y + 1; // assignment : IDENTIFIER = EXPRESSION;The act of assignment takes a copy of a value and stores it in a variable
Object declaration and instantiation.
Chess_Piece bishop1; // CLASSNAME IDENTIFIER; bishop1 = new Chess_Piece(); // IDENTIFIER = new CLASSNAME(PARAMETERLIST); bishop2 = bishop1;
Reference Assignment
For object references, the value of the
memory location is copied:
bishop2 = bishop1; Before ^ | After ^ / \ | / \ bishop1--->| | | bishop1--->| | | B1| | | B1| ,-' `-.| __\ ,-' `-. `-------'| | / `-------' | | ^ | | ^ / \ | | / \ bishop2--->| | | bishop2 | | | B2| | | B2| ,-' `-.| ,-' `-. `-------'| `-------'after the assignment
Methods
A class contains methods; prior to defining our own classes, we must
explore method
definitions
All methods follow the same syntax:
return-type method-name ( formal-parameter-list ) {
statement-list
}
We've seen the main method with
A method definition:
int third_power (int number) {
int cube; // local variable only
cube = number * number * number;
return cube; // matches return_type
} // method third_power
Method Flow of Control
The main method is invoked by the system when you submit the
bytecode to the
interpreter
Each method call returns to the place that called it
main { -->method1() --> }
| ^
| |
| `------------------.
V |
method1 { --> method2() -->}
| ^
V |
method2 {--->}
Parameters
FORMAL-PARAMETER-LIST zero or more of
type name, type name
The parameters in the method definition are called formal parameters
The values passed to a method when it is invoked are called actual parameters
When a parameter is passed, a copy of the value is made and assigned
to the formal
parameter
Both primitive types and object references can be passed as parameters
For objects, the formal parameter becomes an alias of the actual parameter
Defining Classes
The syntax for defining a class is:
class class-name {
declarations
constructors
methods
}
The variables, constructors, and methods of a class are generically called
members of the class
Defining Classes
class Account {
int account_number;
double balance;
Account (int account, double initial) {
account_number = account;
balance = initial;
} // constructor Account
void deposit (double amount) {
balance = balance + amount;
} // method deposit
} // class Account
Constructors
A constructor is a special method that is used to set up a newly created object
often sets the initial values of variables
has the same name as the class
does not return a value
has no return type, not even void
The programmer does not have to define a constructor for a class
Classes and Objects
A class defines the data types for an object, but a class does not store data values
Each object has its own unique data space
The variables defined in a class are called
instance variables because each
instance of the class has its own
All methods in a class have access to all
instance variables of the class
Methods are shared among all objects of a class
Classes and Objects
Class Objects .------------------. .-----------------------. |int account_number|--->| account_number 2908371| |double balance | | balance 573.21 | `------------------'\ `-----------------------' \ .-----------------------. `>| account_number 4113787| | balance 9211.84| `-----------------------'
Encapsulation
You can take one of two views of an object:
internal - the structure of its data, the
algorithms used by its methods
external - the interaction of the object with other objects in the program
From the external view, an object is an
encapsulated entity, providing a set of
specific services
These services define the interface to the
object
Encapsulation
An object should be self-governing
any changes to the object's state (its
variables) should be accomplished by that
object's methods
another object should not be able to
"reach in" and alter an object's state
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
It is a black box.
Encapsulation
An encapsulated object can be thought of as a black box;
its inner workings are hidden to the client
toms_savings .-----------. ----* deposit | | ----* withdraw `-----------' ----* add_interest ----* produce_statement /\ || || .--------. | client | `--------'
Abstraction
Encapsulation is a powerful abstraction
An abstraction hides the right details at the right time
We use abstractions every day:
walking
using a computer
Encapsulation makes an object easy to
manage mentally because its interaction with
clients is limited to a set of well-defined
services
Visibility Modifiers
We accomplish encapsulation through the appropriate use of visibility modifiers
A modifier is a Java reserved word that
specifies particular characteristics of a
programming construct
We've used the modifier final to define a
constant
Java has three visibility modifiers:
public, private, and protected
We will discuss the protected modifier later
Visibility Modifiers
Members of a class that are declared with public visibility can
be accessed from
anywhere
Members of a class that are declared with
private visibility can only be accessed from inside the class
Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package
Java modifiers are discussed in detail in
Appendix F
Visibility Modifiers
As a general rule, no object's data should be declared with public visibility
Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients
Public methods are also called
service methods
Other methods, called support methods, can be defined that assist the service methods;
they should not be declared with public
visibility
Classes and Objects
See Tunes.java
music .-------. ---* add_cds .------. | | ---* print <===| main | `-------' `------'
The static Modifier
The static modifier can be applied to
variables or methods
It associates a variable or method with the class rather than an object
This approach is a distinct departure from the normal way of thinking
about objects
Static Variables
Normally, each object has its own data space
If a variable is declared as static, only one copy of the variable exists for all objects of the class
private static int count;Changing the value of a static variable in one object changes it for all others
Static variables are sometimes called
class variables
Static Methods
Normally, we invoke a method through an
instance (an object) of a class
If a method is declared as static, it can be invoked through the class name; no object needs to exist
For example, the Math class in the java.lang package contains several static mathematical operations
- absolute value
Math.abs (num)- square root
Math.sqrt (num)
Static Methods
The main method is static;
it is invoked by the system without creating an object
Static methods cannot reference instance
variables, because instance variables don't
exist until an object exists
However, they can reference static variables or local variables
Static methods are sometimes called
class methods
Overloaded Methods
Method overloading is the process of using the same method name for multiple methods
The signature of each overloaded method must be unique
The signature is based on the number, type, and order of the parameters
The compiler must be able to determine which version of the method is
being invoked by
analyzing the parameters
The return type of the method is not part of the signature
Overloaded Methods
The println method is overloaded:
println (String s) println (int i) println (double d)etc.
The lines
System.out.println ("The total is:");
System.out.println (total);
invoke different versions of the println method
Overloaded Methods
Constructors are often overloaded to provide multiple ways to set up a new object
Account (int account) {
account_number = account;
balance = 0.0;
} // constructor Account
Account (int account, double initial) {
account_number = account;
balance = initial;
} // constructor Account
See Casino.java
Classes and Objects
See Purchase_Power.java
Manager Purchase_Power Manager ,----------. ,---------. ,-------. ,>| name: | | | | name: |<-----. | | "Jim" |<-. | ,---->| "Bob" | | | `----------' `----jim | | `-------' | | | bob--' | | | Stock_Item | | Stock_Item | | ,-------------. | | ,-------------.| | |name: |<-- beans | | name: || | | "beans" | | | | "franks" || `---product_buyer| | franks --->|product_buyer--' `-------------' | | `--------------' `---------'
Classes and Objects
See Storm.java
RainDrop Storm ,--------. | | current_size 18 <---- drop1 | | | current_size 4 <---- drop2 | | | current_size 12 <---- drop3 | | | current_size 7 <---- drop4 | | | current_size 24 <---- drop5 | | | `--------'
One Manager and One Stock_Item
class Purchase_Power {
private static Manager jim = new Manager ("Jim");
private static Stock_Item beans = new Stock_Item(jim, "Beans");
public static void main (String[] args) {
boolean b = beans.buy(2);
b = beans.buy(2);}}
class Manager {
private String name;
public Manager (String id) { name = id;}
public void order_stock (Stock_Item out)
{out.replenish (10); } }
class Stock_Item {
private int inventory = 0;
private String name;
private Manager product_buyer;
public Stock_Item (Manager c, String p) {
name = p;
product_buyer = c; }
public Stock brand () {return name;}
public boolean buy (int amount) {
boolean success = false;
if (amount <= inventory) {
inventory -= amount;
success = true; }
else
product_buyer.order_stock (this);
return success; }
public void replenish (int amount){inventory += amount;
}}
One Raindrop only
import java.applet.Applet;
import java.awt.Graphics;
import java.util.Random;
public class Storm extends Applet {
private final int MAX_COUNT = 500;
private final int BUSY_WAIT = 50000;
private final int APPLET_SIZE = 200;
private Random position = new Random();
private Raindrop drop1;
private Graphics page;
public void init() {
drop1 = new Raindrop();
setSize (APPLET_SIZE, APPLET_SIZE);
setVisible (true);
} // method init
public void start() {
int count = 1;
int wait;
while (count < MAX_COUNT) {
check_drop (drop1);
count = count + 1;
draw (page);
wait = 0;
while (wait < BUSY_WAIT) {
wait = wait + 1;
} } } // method start
public void check_drop (Raindrop drop) {
if (drop.visible())
drop.ripple();
else {
int x = Math.abs(position.nextInt() % APPLET_SIZE)+1;
int y = Math.abs(position.nextInt() % APPLET_SIZE)+1;
drop.set_position (x, y);
}
} // method check_drop
public void draw (Graphics page) {
page.setColor(getBackground());
page.fillRect (0, 0, APPLET_SIZE, APPLET_SIZE);
page.setColor(getForeground());
drop1.draw (page);
} // method draw
} // class Storm
}
class Raindrop {
private final int MAX_RIPPLE = 30;
private final int RIPPLE_STEP = 2;
private static Random new_size = new Random();
private int current_size = 0;
private int visible_size = 0;
private int x = 1, y = 1;
public boolean visible() {
return current_size < visible_size;
} // method visible
public void set_position(int x_position,int y_position){
x = x_position;
y = y_position;
visible_size =
Math.abs(new_size.nextInt()
% (int)((y+10)/500.0*MAX_RIPPLE))+1;
current_size = 1;
} // method set_position
public void ripple() {
x = x - RIPPLE_STEP/2;
y = y - RIPPLE_STEP/2;
current_size = current_size + RIPPLE_STEP;
} // method ripple
public void draw (Graphics page) {
page.drawOval (x, y, current_size, current_size/2);
} // method draw
} // class Raindrop