Ch03 - Skylight Publishing
Download
Report
Transcript Ch03 - Skylight Publishing
Java Methods
Object-Oriented Programming
and Data Structures
2nd AP edition with GridWorld
Maria Litvin ● Gary Litvin
C h a
p t
e
r
3
Objects and Classes
Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
Objectives:
• See an example of a GridWorld program,
written in OOP style, and discuss the types of
objects used in it
• Learn about the general structure of a class,
its fields, constructors, and methods
• Get a feel for how objects are created and
how to call their methods
• Learn a little about inheritance in OOP
3-2
OOP
• An OO program models the application as a
world of interacting objects.
• An object can create other objects.
• An object can call another object’s (and its
own) methods (that is, “send messages”).
• An object has data fields, which hold values
that can change while the program is running.
3-3
Objects
• Can model real-world objects
• Can represent GUI (Graphical User
Interface) components
• Can represent software entities (events,
files, images, etc.)
• Can represent abstract concepts (for
example, rules of a game, a location on a
grid, etc.)
3-4
Objects in the Bug Runner program
GridWorld
window
Message
display
Menu bar,
menus
Scroll bar
Grid
Locations (in
the grid)
Bugs, flowers,
and rocks
Colors
Control panel
Buttons, slider
3-5
Classes and Objects
• A class is a piece of the program’s source
code that describes a particular type of
objects. OO programmers write class
definitions.
• An object is called an instance of a class.
A program can create and use more than
one object (instance) of the same class.
3-6
Class
Object
• A blueprint for
objects of a
particular type
Attributes
• Defines the
structure (number,
types) of the
attributes
Behaviors
• Defines available
behaviors of its
objects
3-7
Class: Car
Attributes:
String model
Color color
int numPassengers
double amountOfGas
Object: a car
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
3-8
Class
• A piece of the
program’s source
code
• Written by a
programmer
vs.
Object
• An entity in a
running program
• Created when the
program is running
(by the main method
or a constructor or
another method)
3-9
Class
vs.
• Specifies the
structure (the
number and types)
of its objects’
attributes — the
same for all of its
objects
• Specifies the
possible behaviors
of its objects
Object
• Holds specific
values of attributes;
these values can
change while the
program is running
• Behaves
appropriately when
called upon
3-10
CRC Card
• A preliminary description of a class at the
initial stage of program design
Class
Bug
Responsibilities
Occupies a location in
the grid
Moves
Turns
Acts: moves if it can,
otherwise turns.
Actor
Grid
Location
Collaborators
3-11
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 extension .java
Car.java
public class Car
{
...
}
By convention, the
name of a class
(and its source file)
always starts with
a capital letter.
(In Java, all names are case-sensitive.)
3-12
Libraries
• Java programs are usually not written from
scratch.
• There are hundreds of library classes for all
occasions.
• Library classes are organized into packages.
For example:
java.util — miscellaneous utility classes
java.awt — windowing and graphics toolkit
javax.swing — GUI development package
3-13
import
• Full library class names include the package
name. For example:
java.awt.Color
javax.swing.JButton
• import statements at the top of the source file
let you refer to library classes by their short
names:
Fully-qualified
import javax.swing.JButton;
name
...
JButton go = new JButton("Go");
3-14
import (cont’d)
• You can import names for all the classes in a
package by using a wildcard .*:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Imports all classes
from awt, awt.event,
and swing packages
• java.lang is imported automatically into all
classes; defines System, Math, Object,
String, and other commonly used classes.
3-15
import (cont’d)
• GridWorld has its own library (gridworld.jar)
• You need to tell the compiler where to find
GridWorld classes:
import
import
...
import
import
...
info.gridworld.grid.Grid;
info.gridworld.grid.Location;
info.gridworld.actor.Bug;
info.gridworld.actor.Flower;
3-16
SomeClass.java
import ...
import statements
public class SomeClass
{
• Fields
• Constructors
• Methods
}
Class header
Attributes / variables that define the
object’s state; can hold numbers,
characters, strings, other objects
Procedures for constructing
a new object of this class
and initializing its fields
Actions that an object
of this class can take
(behaviors)
3-17
public class Actor
{
private Grid<Actor> grid;
private Location location;
private int direction;
private Color color;
public Actor()
{
color = Color.BLUE;
direction = Location.NORTH;
grid = null;
location = null;
}
...
public void moveTo(Location newLocation)
{
...
}
...
Fields
Constructor(s)
Methods
}
3-18
Fields
• A.k.a. instance variables
• Constitute “private memory” of an object
• Each field has a data type (int, double, String,
Color, Location, etc.)
• Each field has a name given by the
programmer
3-19
You name it!
Fields (cont’d)
private [static] [final] datatype name;
Usually
private
May be present:
means the field is
shared by all
objects in the class
int, double, etc., or an
object: String, Location,
Color
May be present:
means the field
is a constant
private Location location;
3-20
Constructors
• Short procedures for creating objects of a
class
•
•
•
•
Always have the same name as the class
Initialize the object’s fields
May take parameters
A class may have several constructors that
differ in the number and/or types of their
parameters
3-21
Constructors (cont’d)
public class Location
{
private int row;
private int col;
The name of a constructor
is always the same as the
name of the class
...
public Location (int r, int c)
{
A constructor can take parameters
row = r;
col = c;
}
...
}
Initializes fields
3-22
Constructors (cont’d)
// BugRunner.java
...
Location loc = new Location(3, 5);
...
public class Location
{
An object is created with
the new operator
The number, order, and
types of parameters must
match
...
public Location (int r, int c)
{
...
}
...
Constructor
}
3-23
Constructors (cont’d)
JButton go = new JButton("Go");
3-24
Methods
• Call them for a particular object:
ActorWorld world = new ActorWorld();
Bug bob = new Bug();
world.add (new Location(3, 5), bob);
bob.move( );
bob.turn( );
3-25
Methods (cont’d)
• The number and types of parameters (a.k.a.
arguments) passed to a method must match
method’s parameters:
public void drawString ( String msg, int x, int y )
{
...
}
g.drawString ("Welcome", 120, 50);
3-26
Methods (cont’d)
• A method can return a value to the caller
• The keyword void in the method’s header
indicates that the method does not return any
value
public void drawString ( ... )
{
...
}
3-27
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)
3-28
Methods (cont’d)
• 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
public method
private method
3-29
Inheritance
• In OOP a programmer can create a new class
by extending an existing class
Superclass
(Base class)
subclass extends
superclass
Subclass
(Derived class)
3-30
Inheritance (cont’d)
Actor
Bug extends Actor
Bug
UTurnBug extends
Bug
UTurnBug
3-31
A Subclass...
• inherits fields and methods of its
superclass
• can add new fields and methods
• can redefine (override) a method of the
superclass
• must provide its own constructors, but
calls superclass’s constructors
• does not have direct access to its
superclass’s private fields
3-32
public class UTurnBug extends Bug
{
public UTurnBug (Color bugColor)
{
setColor (bugColor);
}
...
public void turnAround ()
{
turn(); turn(); turn(); turn();
// Or: setDirection (getDirection() + 180);
}
...
Constructor
A new
method
}
3-33
Review:
• Name a few objects used in GridWorld’s
BugRunner.
• Name a few library classes used in
GridWorld.
• What are import statements used for?
• What is a field? A constructor? A method?
• Which operator is used to construct an
object?
3-34
Review (cont’d):
• What is the difference between private and
public methods?
• Why are fields usually private?
• What is inheritance?
• Can a subclass add new fields? New
methods?
3-35