Chapter 3 - Objects and classes. This chapter gives an introduction to the main Java and OOP concepts but does not require their full understanding. In terms of grasping the big picture, each student proceeds at his or her own pace. The same concepts are covered later in more depth. Here students get a general idea of how things are put together, get a feel for OOP, and work on exercises that require rearranging small pieces of code.
Trang 1TNT NS Java Methods
METHODS
Object-Oriented Programming and Data Structures
2nd AP edition with GridWorld Maria Litvin e Gary Litvin | pit Cì ¡ @@I)| ‹ A we or <
Objects and Classes
Trang 2
Objectives:
See an example of a GridWorld program,
written in OOP style, and discuss the types of objects used init
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
Trang 3
OOP
e An OO program models the application as a world of interacting objects
e An object can create other objects
e An object can call another object’s (and Its own) methods (that Is, “send messages’) e An object has data fields, which hold values
that can change while the program Is running
Trang 4
Objects
e Can model real-world objects
e Can represent GUI (Graphical User Interface) components
e Can represent software entities (events, files, Images, etc.)
e Can represent abstract concepts (for
example, rules of agame, a location ona grid, etc.)
Trang 5Objects in the Bug Runner program
GridWorld = | ~~ @ Griaworta [.JIp]k
WI n d OW World Location Help
Trang 6Classes and Objects
° A class IS a plece of the program’s source code that describes a particular type of
objects OO programmers write class definitions
e An object is called an instance of a class A program can create and use more than one object (instance) of the same class
Trang 8Class: Car Object: a car hs R10 10001719 TA , « *, ` ? eS aoe _— o RB) ©) Attributes: Attributes:
String model model = "Mustang"
Color color color = Color YELLOW
int numPassengers numPassengers = 0
double amountOfGas amountOfGas = 16.5
Behaviors: Behaviors:
Add/remove a passenger | <« e Get the tank filled
Report when out of gas
Trang 9
Class vs Object
e A piece of the program's source e Anentity ina running program code
e Written by a e Created when the
programmer program Is running
(oy the main method or a constructor or another method)
Trang 10
Class vs Object
° Specifies the ¢ Holds specific
Structure (the values of attributes;
number and types) these values can
of its objects’ change while the
attributes — the program Is running
same for all of its objects
s Specifies the e Behaves
possible behaviors appropriately when
of its objects called upon
Trang 11CRC Card
e A preliminary description of a class at the Initial stage of program design Class ` Responsibilit ` les Bug
Occupies a location in Actor
Trang 12Classes and Source Files
e Each class Is stored in a separate file
e The name of the file must be the same as the
name of the class, with the extension java
/ Car java By convention, the
public class Car 4} name of a class
{ | (and its source file)
Trang 13Libraries e Java programs are usually not written from scratch e There are hundreds of library classes for all occasions e Library classes are organized into packages For example:
Trang 14Import
e 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");
Trang 15Import (cont'd)
e You can import names for all the classes ina package by using a wildcard *:
Import Java.awI.*; Imports all classes
import java.awt.event.*: from awt, awt.event,
Import javax.swing.*; and swing packages
° java.lang is imported automatically into all classes; defines System, Math, Object,
String, and other commonly used classes
Trang 16import (cont'd)
Trang 17
⁄ SomeClass.java \_
Import import statements
public class SomeClass ——\ Class header
Ẳ Attributes / variables that define the
se Fields ——— object’s state; can hold numbers,
characters, strings, other objects Procedures for constructing
° Constructors a new object of this class
and initializing its fields Actions that an object
se Methods of this class can take
\ (behaviors)
Trang 18
public class Actor
Ẳ
private Grid<Actor> grid; Fields private Location location;
Trang 19Fields
e A.k.a instance variables
° Constitute “private memory” of an object
e Each field has a data type (int, double, String, Color, Location, etc.)
Trang 20You name it! Fields (cont'd) \ private [static] [final] datatype name; Usually - private int, double, etc., or an object: String,
May be present: Location, Color
means the field is
shared by all May be present:
objects in the class means the field
is a constant
private Location location;
Trang 21Constructors e Short procedures for creating objects of a class
e Always have the same name as the class e Initialize the object’s fields
e May take parameters
e Aclass may have several constructors that differ in the number and/or types of their
parameters
Trang 22Constructors (cont'd)
public class Location <«
Ẳ
Trang 23Constructors (cont'd)
An object is created with // BugR geet Java [ i the new operator
Location loc = new Location(3, 5);
| The number, order, and
Trang 24lu fi |] Java™ Platform —' c— | Constructors (cont'd) Naeclaaac —— saul (>) JAAD ReESUN "—— JAXBSource ^ JButton JCheckBox IMherkRayvMieniiltam Constructor Summary JButton () Creates a button with no set text or icon JButton(Action a) Creates a button where properties are taken from the Action supplied JButton(Icon icon) Creates a button with an icon — > | TButton(sString text) Creates a button with text
JButton(String text, Icon icon)
Trang 25Methods
e Call them for a particular object:
ActorWorld world = new ActorWorld();
Bug bob = new Bug0);
world.add (new Location(3, 5), bob);
bob.move( ); bob.turn( );
Trang 26Methods (cont'd)
Trang 27Methods (cont'd)
e A method can return a value to the caller
e The keyword void in the method’s header
indicates that the method does not return any value
public void drawString ( )
Trang 28Encapsulation and Information Hiding
e Aclass interacts with other classes only through constructors and public methods
e Other classes do not need to know the
mechanics (implementation details) of a class to use It effectively
e Encapsulation facilitates team work and
program maintenance (making changes to the code)
Trang 29
Methods (cont'd)
e Constructors and methods can call other
public and private methods of the same class ¢ Constructors and methods can call only
Trang 30Inheritance
Trang 32A Subclass e inherits fields and methods of its Superclass
s can add new fields and methods
s can redefine (override) a method of the Superclass
° musf provide Ifs own constructors, Dbut calls superclass's constructors
e does not have direct access to Its
Superclass’s private fields
Trang 33public class UTurnBug extends Bug { public UTurnBug (Color bugColor) Constructor { setColor (bugColor); } public void turnAround () A new { method
turn(); turn(); turn(); turn();
// Or: setDirection (getDirection() + 180);
}
Trang 34Review: e Name a few objects used tin GridWorld’s BugRunner e Name a few library classes used In GridWorld
e What are import statements used for?
e What Is a field? A constructor? A method? e Which operator is used to construct an
object?