CHAPTER 2
An Introduction to Objects
and Classes
Classes
Class: Set of objects with the
same behavior, describes
characteristics and behavior of
an object.
Each class can have instances of
multiple objects
Written in a file all its own
Objects
Object: real world entity that you
can manipulate in your
programs (by invoking methods)
Each object belongs to a class
Object vs Class
Object
is an instance of a class
Cookie
Class
is a blueprint for an
object
Cookie
Cutter
Create an instance of an
object
Instantiation
of an object creates an
instance of an object and the
parameters passed into the
constructor will initialize the private
instance fields.keyword new
Car
c = new Car(blue, 1999);
An Object
An
object has data fields, which hold values
that can change while the program is
running. A piece of data maybe another
object.
An
object has a set of methods that can
process messages of certain types. A method
can change the objects state, send
messages to other objects, and create new
objects.
Class
blueprint for
objects of a
particular type
Defines the
structure
(number, types)
of the attributes
Defines available
behaviors of its
objects
Object
Attributes
Behaviors
Class: Car
Attributes:
String model
Color color
int numPassengers
double amountOfGas
car
Object: my
Attributes:
model = "Mustang"
color = Color.YELLOW
numPassengers = 0
amountOfGas = 16.5
Behaviors:
Behaviors:
Add/remove a passenger
Get the tank filled
Report when out of gas
Class
Written by a
programmer
Example: class Robot which
keeps track of its initial
location, current location
and direction facing with
behaviors such as turn and
step forward.
vs.
Object
Created when the
program is
running (by the
main method or a
constructor or
another method)
Example: R2D2 or WallE
OOP
Object-Oriented Programming
An
OO program models the application
as a world of interacting objects.
An
An
object can create other objects.
object can call another objects
(and its own) methods (that is, send
messages).
OOP Benefits
Facilitates
team development
Easier
to reuse software components and
write reusable software
Easier
GUI (Graphical User Interface) and
multimedia programming
Objects in the Dance Studio
Program
Dance Studio
window
Band
Foot
Dance selection
pulldown list
Dancer
Go / Stop button
Control panel
Dance floor
Positioning
button
Waltz, etc.
Dance step
Dance group
Classes and Source Files
Each
class is stored in a separate file
The name of the file must be the same
as the name of the class, with the
Car.java
extension .java
By convention, the
public class Car
{
...
}
name of a class
(and its source file)
always starts with
a capital letter.
(In Java, all names are case-sensitive.)
3 parts to every class
Fields/Instance
Fields/Instance
Variables /private data
members/Attributes
Methods/Behaviors
Constuctors
SomeClass.java
import ...
import statements
public class SomeClass
Class header
{
Fields
Attributes / variables that define the
objects state; can hold numbers,
characters, strings, other objects
Constructors
Methods
Procedures for constructing
a new object of this class
and initializing its fields
Actions that an object
of this class can take
(behaviors)
Object Diagrams and
Access to all the parts
public constructor
___________
private fields
____________
public method
___________
____________
____________
public method
___________
Part 1 - Fields
Constitute
private memory of an
object
Each field has a data type (int, double,
String, boolean, char, or another type
of object)
Each field has a name given by the
programmer
Fields
Should
always be of private access type
Can
be used by any method within the same
class.
From
within the class, just refer to them by
their names.
From outside the class in another file such as
main, the only way we can access them is via
methods of the class.
Syntax 2.6 : Instance Field
Declaration
accessSpecifier
class ClassName
{
...
accessSpecifier fieldType fieldName;
...
accessSpecifier could be private, public,
protected
fieldType could be int, double, String,
boolean, char
You name it!
Fields (contd)
private datatype name;
Usually
private
int, double, etc., or an
object: String, Image,
Foot
private double cost;
private String name;
private int age;
An objects STATE
Each
object of a class has its own set of
instance fields.
An
object stores its state in one or more
variables called INSTANCE FIELDS/DATA.
What
is in these private variables
indicate the STATE of an object.
Part 2 - Constructors
A
constructor is special
procedure for constructing an
object.
PURPOSE:
Initialize the
objects fields
Constructors
Always
have the same name as the
Always
public
class
No
return type
May
or may not take parameters
Constructors
public class Car()
{
public Car(int m)
{
miles = m;
}
. . .
}
Syntax 2.7 : Constructor
Implementation
To define the behavior of a constructor,
which is used to initialize the instance
fields of newly created objects
Using the new keyword
Invoked in new expression
new Car(15000)
For now we will construct an
object in the main file.
More on constructors
Not
a method
overloading
common practice, same
signature, different parameter lists
(method signature = name of method and parameter list)
class may have several constructors
that differ in the number and/or types
of their parameters
Overloaded Constructors
These are all different
public Car ( )
no parameters called
the
default constructor initializes
all private data to 0 or null.
public Car (int miles)
public Car (String name, int miles)
public Car (int miles, String name)
PUBLIC INTERFACE OF A
CLASS
The
constructors
and methods of a
class which can be
seen by all.
Public Access Specifier
Constructors
and methods can call
other public and private methods
of the same class.
Constructors and methods can call
only public methods of another
class.
Class X
Class Y
private field
public method
private method
public method
3. Methods
Example:
one of the behaviors of an
object may be to compute something.
All the objects of the class will use the
same formula for the computation, but
the result may depend on the specific
values of objects attributes at the
time of the computation.
Method Definition
Written in the class
access specifier (We will always use public)
return type (int,double,char,String,boolean,void,
or another objects type MUCH LATER)
method name (meaningful and lowercase)
list of parameters (need types and names
separated by commas)
method body in { }
Sample method
public double addIt (int number)
{
total = total + number;
return total;
}
Name each colored part
We can also have overloaded methods
public double addIt(int x, int y)
Methods (contd)
A
method can return a value to the
caller again for now this is just the
main file.
The keyword void in the methods
header indicates that the method does
not return any value
public void moveSideways(int distance)
{
...
Method Body is always in
}
curly braces
2 Types of Methods
Accessor
will access a private
variable and typically RETURN it,
make sure the return type
matches the data type of the field
Modifier/Mutator
will change
what is in a private field and
typically RETURN void.
METHOD PARAMETERS
These
are the values you pass into a
method.
They will be used inside the method in
some way.
They are only a COPY of the variable
from where you passed it in from.
They can have different names from
where you passed them in from.
Syntax 2.5: The return
Statement
return expression; or return;
Example:
return message;
Purpose:
To specify the value that a method returns,
and exit the method immediately.
The
return line ends the method action
and returns program control to where it
was called from.
METHOD IMPLEMENTATION
A
CALL to a method
For instance System.out.printl();
is a call to the method println in the
system class.
Use a dot
For now we will call a method from our main
file.
Objects
Contain
1.
properties/variables/fields
2. methods/behaviors
3. constructors
Object Construction
In main for now
To create an new object:
new className(parameters without types)
This calls the constuctor which
matches the same number and
type of parameters and initializes
the private data fields to the
parameter values passed in.
Object Construction
Examples
new Rectangle(5, 10, 20, 30)
this would match the constructor:
public Rectangle(int x,int y,int w,int h)
new Car("BMW 540ti", 2004)
this would match the constructor:
public Car(String name, int year)
A Rectangle Object
an OBJECT DIAGRAM
Object Reference
We
need to be able to reference a
particular object to so we can use it
and its data and its methodsto do
this we must name it.
Called creating an object reference.
Each object will most likely have a
different name or reference to it.
Creating an Object Variables or
Object Reference
A
container that stores the location of
an object
MUST be initialized before you can use it
ClassName referenceName =
The right side of the equals sign now has an object
construction callsee previous slides.
Object Variables/Reference
Declare and optionally initialize:
Rectangle crispyCrunchy;
This only declares an object
reference, it does NOT create the
object itself until you use = new
Right now it refers to no object
BETTER KNOWN AS NULL
To use an object variable
Use
the reference name along with a
dot and a method call from that class.
Example:
r is a reference to a Rectangle
as in previous slide.
r.GetArea( );
2 object references referring to
the same object
Common
gotcha on AP multiple
choice questions (and on my tests)
Rectangle
r = new
Rectangle(5,10,20,30);
Rectangle cerealBox = r;
See
what happens here on the next slide.
They both refer to the EXACT same object, not
a copy they are the SAME OBJECT.
Two Object Variables
Referring to the Same Object
Programs can use objects in
the following ways
To
construct an object with the new
keyword
to
store object references in an object
variable
to
call methods on an object variable
Testing a Class/Driver
class
Test class: a class with a main method that
contains statements to test another class.
Typically carries out the following steps:
Construct
one or more objects of the
class that is being tested.
Invoke one or more methods.
Print
out one or more results
VARIABLES
Lots
of different kind of variables.
So far we have discussed:
private instance variables in a class
object reference variables
parameters being passes into
methods or
constructors.
There are more
Local Variables - used
anywhere
created
in a block of code
enclosed within a set of curly
braces.
Could be in a method
Could be in the main class file
They exist only within that block
of code die upon closing brace
General Definition of a
Variable
An
item of information in memory
whose location is identified by a name.
Holds
Every
data of some sort
variable has a type which defines
what kind of information it will hold,
defines how much memory to set aside.
General Definition of a
Variable
Instance
fields -Do not need to be
initialized, numbers default to zero,
strings default to null.
Local
variables NEED to be initialized
to something.
Declaration vs Definition
age
int age ;
int age = 22;
age
22
Syntax 2.2: Variable
Definition
TypeName variableName;
TypeName variableName = expression;
Example:
Rectangle cerealBox;
String name ="Dave";
int x = 10;
Purpose:
To define a new variable of a particular type
and optionally supply an initial value
Naming Conventions for
Variables
Letters,
digits, and underscores
No symbols
No reserved words
Cant start with a digit
case sensitive (upper/lower)
Class
Name Variables - must be
Capitalized
Variable Catagories
class first letter capitalized
constant set only once never changed all capitalized
private instance field mySomething or specific name
variable noun
temporary variable - letter
accessor method verb getter
modifier method verb setter
method verb
Reserved Words
In
Java a number of words are reserved for a
special purpose.
Reserved
words use only lowercase letters.
Reserved
words include:
primitive data types: int, double, char, boolean, etc.
storage modifiers: public, private, static, final, etc.
control statements: if, else, switch, while, for, etc.
built-in constants: true, false, null
There
are about 50 reserved words total.
Programmer-Defined Names
In
addition to reserved words, Java
uses standard names for library
packages and classes:
String, Graphics, javax.swing, JApplet,
JButton, ActionListener, java.awt
The
programmer gives names to his or
her classes, methods, fields, and
variables.
Note
Do NOT make a class called
System it already exists you
overwrite it and loss all functionality.
Names (contd)
Programmers
follow strict style conventions.
Style:
Names of classes begin with an
uppercase letter, subsequent words are
capitalized:
public class FallingCube
Style:
Names of methods, fields, and
variables begin with a lowercase letter,
subsequent words are capitalized.
private final int delay = 30;
public void dropCube()
Names (contd)
Method
names often sound like verbs:
setBackground, getText, dropCube, start
Field
names often sound like nouns:
cube, delay, button, whiteboard
Constants
sometimes use all caps:
PI, CUBESIZE
It
is OK to use standard short names
for temporary throwaway variables:
i, k, x, y, str
Package
Package:
a set of libraries with
many RELATED classes of
prewritten code
To
import a class from a package for
use in a program
Syntax 2.3 : Importing a
Class from a Package
importpackageName.ClassName
Example:
import java.awt.Rectangle;
We
dont need to import anything
with the System class in it,
done automatically.
ENCAPSULATION
Keeping
things hidden as much as possible
to keep things bug free
Benefit: cant accidentally put an object into
an incorrect state.
Wrapping up variables and methods in such
a way so that only those things relevant to
the outside world are visible.
Hiding object data and providing
methods which access them (private
data and public methods.)
Encapsulation and
Information Hiding
A
class interacts with other classes only
through constructors and public methods
Other classes do not need to know the
mechanics (implementation details) of a
class to use it effectively
Encapsulation facilitates team work and
program maintenance (making changes to
the code)
ABSTRACTION
Strip
away to find
the essential
features of an
object.
Designing the Public
Interface
Behavior of bank account:
deposit money
withdraw money
get balance
Methods of BankAccount class:
deposit
withdraw
getBalance
Javadoc
Automatically
generates a set of HTML
pages that describe the class
utility which formats your comments
into a new set of documents that you
can view in a web browser
automatically creates hyperlinks to
other classes and methods
Javadoc Method Summary
Javadoc Method Detail
3 reasons to comment
First
sentence used in summary table of all
methods, javadoc with a description of each.
Spend more time deciding whether or not to
do it than it does just to do it.
Write method comment first to see if you
understand what you need to program.
Styles /*for multiple lines*/
//..once for each line
JavaDoc
Comments
Comments
are notes in plain English
inserted in the source code.
Comments
are used to:
document the programs purpose, author,
revision history, copyright notices, etc.
describe fields, constructors, and methods
explain obscure or unusual places in the code
temporarily comment out fragments of code
Formats for Comments
A
block comment is placed between /*
and */ marks:
/* Exercise 5-2 for Java Methods
Author: Miss Brace
Date: 3/5/2010
Rev. 1.0
*/
single-line comment goes from // to
the end of the line:
wt *= 2.2046;
// Convert to kilograms
Explicit and Implicit
Parameters
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
}
balance is the balance of the object to the left of the
dot:
momsSavings.withdraw(500)
means
double newBalance = momsSavings.balance amount;
momsSavings.balance = newBalance;
Designing and Implementing
a Class
1. What are you asked to do with an object,
list of operations needed.
2. Find names for the methods.
3. Document the public interface.
4. Determine instance variables.
5. Determine constructors.
6. Implement methods one at a time, easiest
first.
7. Test class, apply method calls.