CSO Gaddis Java Chapter06 7e
CSO Gaddis Java Chapter06 7e
7th Edition
Chapter 6
A First Look at Classes
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Chapter Topics
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Objects and Classes (1 of 8)
• An object exists in memory, and performs a
specific task.
• Objects have two general capabilities:
– Objects can store data. The pieces of data stored in
an object are known as fields.
– Objects can perform operations. The operations that
an object can perform are known as methods.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Objects and Classes (2 of 8)
• You have already used the following objects:
– Scanner objects, for reading input
– Random objects, for generating random numbers
– PrintWriter objects, for writing data to files
• When a program needs the services of a
particular type of object, it creates that object in
memory, and then calls that object's methods
as necessary.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Objects and Classes (3 of 8)
• Classes: Where Objects Come From
– A class is code that describes a particular type of
object. It specifies the data that an object can hold
(the object's fields), and the actions that an object
can perform (the object's methods).
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Objects and Classes (4 of 8)
• When a program is running, it can use the class
to create, in memory, as many objects of a
specific type as needed.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Objects and Classes (5 of 8)
This expression creates a
Example: Scanner object in memory.
keyboard Scanner
variable object
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Objects and Classes (6 of 8)
This expression creates a
Example: Random object in memory.
rand Random
variable object
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Objects and Classes (7 of 8)
This expression creates a
Example: PrintWriter object in memory.
outputFile PrintWriter
variable object
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Objects and Classes (8 of 8)
• The Java API provides many classes
– So far, the classes that you have created objects
from are provided by the Java API.
– Examples:
▪ Scanner
▪ Random
▪ PrintWriter
• See ObjectDemo.java
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Packages and import Statements
• Classes in the Java API are organized into
packages.
• Explicit and Wildcard import statements
– Explicit imports name a specific class
▪ import java.util.Scanner;
– Wildcard imports name a package, followed by an *
▪ import java.util.*;
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Some Java Standard Packages
Package Description
java.io Provides classes that perform various types of input and output.
java.lang Provides general classes for the Java language. This package is
automatically imported.
java.net Provides classes for network communications.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Writing a Class, Step by Step (1 of 2)
• A Rectangle object will have the following
fields:
– length. The length field will hold the rectangle’s
length.
– width. The width field will hold the rectangle’s
width.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Writing a Class, Step by Step (2 of 2)
• The Rectangle class will also have the
following methods:
– setLength. The setLength method will store a
value in an object’s length field.
– setWidth. The setWidth method will store a
value in an object’s width field.
– getLength. The getLength method will return the
value in an object’s length field.
– getWidth. The getWidth method will return the
value in an object’s width field.
– getArea. The getArea method will return the area
of the rectangle, which is the result of the object’s
length multiplied by its width.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
UML Diagram
• Unified Modeling Language (UML) provides a
set of standard diagrams for graphically
depicting object-oriented systems.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
UML Diagram for Rectangle class
Rectangle
- length
- width
+ setLength(double)
+ setWidth(double)
+ getLength() : double
+ getWidth() : double
+ getArea() : double
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Writing the Code for the Class Fields
public class Rectangle
{
private double length;
private double width;
}
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Access Specifiers
• An access specifier is a Java keyword that indicates
how a field or method can be accessed.
• public
– When the public access specifier is applied to a class
member, the member can be accessed by code inside the
class or outside.
• private
– When the private access specifier is applied to a class
member, the member cannot be accessed by code outside the
class. The member can be accessed only by methods that are
members of the same class.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Header for the setLength Method
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Writing and Demonstrating the
setLength Method
/**
The setLength method stores a value in the
length field.
@param len The value to store in length.
*/
public void setLength(double len)
{
length = len;
}
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Calling the setLength Method
box.setLength(10.0);
object's area.
*/
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Data Hiding (1 of 2)
• An object hides its internal, private fields from
code that is outside the class that the object is
an instance of.
• Only the class's methods may directly access
and make changes to the object’s internal data.
• Code outside the class must use the class's
public methods to operate on an object's
private fields.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Data Hiding (2 of 2)
• Data hiding is important because classes are
typically used as components in large software
systems, involving a team of programmers.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Stale Data (1 of 2)
• Some data is the result of a calculation.
• Consider the area of a rectangle.
– length × width
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Stale Data (2 of 2)
• Rather than use an area variable in a Rectangle
class:
public double getArea()
{
return length * width;
}
• This dynamically calculates the value of the rectangle’s
area when the method is called.
• Now, any change to the length or width variables will
not leave the area of the rectangle stale.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
UML Data Type and Parameter Notation (1
of 4)
• UML diagrams are language independent.
• UML diagrams use an independent notation to
show return types, access modifiers, etc.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
UML Data Type and Parameter Notation (2
of 4)
• UML diagrams are language independent.
• UML diagrams use an independent notation to
show return types, access modifiers, etc .
Variable types are
placed after the
Rectangle variable name,
separated by a colon.
- width : double
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
UML Data Type and Parameter Notation (3
of 4)
• UML diagrams are language independent.
• UML diagrams use an independent notation to
show return types, access modifiers, etc.
Method return types
Rectangle are placed after the
method declaration
name, separated by a
colon.
- width : double
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
UML Data Type and Parameter Notation (4
of 4)
• UML diagrams are language independent.
• UML diagrams use an independent notation to
show return types, access modifiers, etc.
Method parameters
are shown inside the Rectangle
parentheses using the
same notation as
variables. - width : double
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Converting the UML Diagram to Code
(1 of 3)
• Putting all of this information together, a Java
class file can be built easily using the UML
diagram.
• The UML diagram parts match the Java class
file structure.
class header
ClassName
{
Fields Fields
Methods Methods
}
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Converting the UML Diagram to Code
(2 of 3)
The structure of the class can be compiled public class Rectangle
{
and tested without having bodies for the private double width;
methods. Just be sure to put in dummy private double length;
return values for methods that have a
return type other than void. public void setWidth(double w)
{
}
Rectangle public void setLength(double len)
{
- width : double }
public double getWidth()
- length : double { return 0.0;
}
public double getLength()
+ setWidth(w : double) : void { return 0.0;
+ setLength(len : double): void }
+ getWidth() : double public double getArea()
{ return 0.0;
+ getLength() : double }
+ getArea() : double }
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Converting the UML Diagram to Code
(3 of 3)
Once the class structure has been tested, public class Rectangle
{
the method bodies can be written and
private double width;
tested. private double length;
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Class Layout Conventions
• The layout of a source code file can vary by
employer or instructor.
• A common layout is:
– Fields listed first
– Methods listed second
▪ Accessors and mutators are typically grouped.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Instance Fields and Methods (1 of 2)
• Fields and methods that are declared as
previously shown are called instance fields and
instance methods.
• Objects created from a class each have their
own copy of instance fields.
• Instance methods are methods that are not
declared with a special keyword, static.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Instance Fields and Methods (2 of 2)
• Instance fields and instance methods require
an object to be created in order to be used.
• See example: RoomAreas.java
• Note that each room represented in this
example can have different dimensions.
Rectangle kitchen = new Rectangle();
Rectangle bedroom = new Rectangle();
Rectangle den = new Rectangle();
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
States of Three Different Rectangle Objects
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Constructors (1 of 2)
• Classes can have special methods called
constructors.
• A constructor is a method that is automatically
called when an object is created.
• Constructors are used to perform operations at
the time an object is created.
• Constructors typically initialize instance fields
and perform other object initialization tasks.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Constructors (2 of 2)
• Constructors have a few special properties that
set them apart from normal methods.
– Constructors have the same name as the class.
– Constructors have no return type (not even void).
– Constructors may not return any values.
– Constructors are typically public.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Constructor for Rectangle Class
/**
Constructor
@param len The length of the rectangle.
@param w The width of the rectangle.
*/
public Rectangle(double len, double w)
{
length = len;
width = w;
}
Rectangle
Notice there is no
return type listed
- width : double for constructors.
- length : double
+Rectangle(len:double, w:double)
+ setWidth(w : double) : void
+ setLength(len : double): void
+ getWidth() : double
+ getLength() : double
+ getArea() : double
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Uninitialized Local Reference Variables
• Reference variables can be declared without being
initialized.
Rectangle box;
• This statement does not create a Rectangle object,
so it is an uninitialized local reference variable.
• A local reference variable must reference an object
before it can be used, otherwise a compiler error will
occur.
box = new Rectangle(7.0, 14.0);
• box will now reference a Rectangle object of length
7.0 and width 14.0.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The Default Constructor (1 of 2)
• When an object is created, its constructor is
always called.
• If you do not write a constructor, Java provides
one when the class is compiled. The
constructor that Java provides is known as the
default constructor.
– It sets all of the object’s numeric fields to 0.
– It sets all of the object’s boolean fields to false.
– It sets all of the object’s reference variables to the
special value null.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The Default Constructor (2 of 2)
• The default constructor is a constructor with no
parameters, used to initialize an object in a
default configuration.
• The only time that Java provides a default
constructor is when you do not write any
constructor for a class.
– See example: First version of Rectangle.java
• A default constructor is not provided by Java if
a constructor is already written.
– See example: Rectangle.java with Constructor
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Writing Your Own No-Arg Constructor
• A constructor that does not accept arguments is
known as a no-arg constructor.
• The default constructor (provided by Java) is a
no-arg constructor.
• We can write our own no-arg constructor
public Rectangle()
{
length = 1.0;
width = 1.0;
}
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The String Class Constructor (1 of 2)
• One of the String class constructors accepts a
string literal as an argument.
• This string literal is used to initialize a String
object.
• For instance:
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The String Class Constructor (2 of 2)
• This creates a new reference variable name
that points to a String object that represents
the name “Michael Long”
• Because they are used so often, String
objects can be created with a shorthand:
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Passing Objects as Arguments
• When you pass a object as an argument, the
thing that is passed into the parameter variable
is the object's memory address.
• As a result, parameter variable references the
object, and the receiving method has access to
the object.
• See DieArgument.java
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Overloading Methods and Constructors
• Two or more methods in a class may have the
same name as long as their parameter lists are
different.
• When this occurs, it is called method
overloading. This also applies to constructors.
• Method overloading is important because
sometimes you need several different ways to
perform the same operation.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Overloaded Method add
public int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Rectangle Class Constructor Overload
(2 of 2)
If we were to add the no-arg constructor we wrote
previously to our Rectangle class in addition to
the original constructor we wrote, what would
happen when we execute the following calls?
The first call would use the no-arg constructor and box1
would have a length of 1.0 and width of 1.0.
The second call would use the original constructor and
box2 would have a length of 5.0 and a width of 10.0.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The BankAccount Example
BankAccount.java BankAccount
AccountTest.java
-balance:double
+BankAccount()
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Scope of Instance Fields
• Variables declared as instance fields in a class
can be accessed by any instance method in the
same class as the field.
• If an instance field is declared with the public
access specifier, it can also be accessed by
code outside the class, as long as an instance
of the class exists.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Shadowing
• A parameter variable is, in effect, a local variable.
• Within a method, variable names must be unique.
• A method may have a local variable with the same
name as an instance field.
• This is called shadowing.
• The local variable will hide the value of the instance
field.
• Shadowing is discouraged and local variable names
should not be the same as instance field names.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Object Oriented Design
Finding Classes and Their Responsibilities (1 of 2)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved