0% found this document useful (0 votes)
5 views

Chapter 6 Notes

Chapter 6 introduces the concept of objects and classes in programming, explaining how objects store data and perform operations. It covers the creation of simple classes, instance fields, methods, constructors, and the importance of access specifiers for data encapsulation. Additionally, the chapter discusses the use of UML diagrams for visualizing class structures and emphasizes the significance of data hiding and avoiding stale data in software development.

Uploaded by

danil.buzhor2012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chapter 6 Notes

Chapter 6 introduces the concept of objects and classes in programming, explaining how objects store data and perform operations. It covers the creation of simple classes, instance fields, methods, constructors, and the importance of access specifiers for data encapsulation. Additionally, the chapter discusses the use of UML diagrams for visualizing class structures and emphasizes the significance of data hiding and avoiding stale data in software development.

Uploaded by

danil.buzhor2012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

CHAPTER 6

A First Look
at Classes

Copyright © 2016 Pearson Education, Inc., Hoboken NJ


Chapter Topics
Chapter 6 discusses the following main topics:
– Objects and Classes
– Writing a Simple Class, Step by Step
– Instance Fields and Methods
– Constructors
– Passing Objects as Arguments
– Overloading Methods and Constructors
– Scope of Instance Fields
– Packages and import Statements

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-2
Objects and Classes
• 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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-3
Objects and Classes
• 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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Objects and Classes
• 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).

– You can think of a class as a code "blueprint" that


can be used to create a particular type of object.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Objects and Classes
• When a program is running, it can use the class
to create, in memory, as many objects of a
specific type as needed.

• Each object that is created from a class is called


an instance of the class.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Objects and Classes
This expression creates a
Example: Scanner object in memory.

Scanner keyboard = new Scanner(System.in);

The object's memory address


is assigned to the keyboard
variable.

keyboard Scanner
variable object

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Objects and Classes
This expression creates a
Example: Random object in memory.

Random rand = new Random();

The object's memory address is


assigned to the rand variable.

rand Random
variable object

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Objects and Classes
This expression creates a
Example: PrintWriter object in memory.

PrintWriter outputFile = new PrintWriter("numbers.txt");

The object's memory address is assigned to


the outputFile variable.

outputFile PrintWriter
variable object

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Objects and Classes
• 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

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class ObjectDemo
{
public static void main(String[] args) throws IOException
{
int maxNumbers; // Max number of random numbers
int number; // To hold a random number
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
PrintWriter outputFile = new PrintWriter("numbers.txt");
System.out.print("How many random numbers should I write?");
maxNumbers = keyboard.nextInt();
for (int count = 0; count < maxNumbers; count++)
{
number = rand.nextInt();
outputFile.println(number);
}
outputFile.close();
System.out.println("Done");
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Writing a Class, Step by Step
• 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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-12
Writing a Class, Step by Step
• 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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-13
UML Diagram
• Unified Modeling Language (UML) provides a
set of standard diagrams for graphically
depicting object-oriented systems.

Class name goes here

Fields are listed here

Methods are listed here

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-14
UML Diagram for
Rectangle class

Rectangle

length
width

setLength()
setWidth()
getLength()
getWidth()
getArea()

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-15
Writing the Code for the Class Fields

public class Rectangle


{
private double length;
private double width;
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-16
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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-17
Header for the setLength Method
Return Notice the word
Type static does not
Access Method appear in the method
specifier Name header designed to work
on an instance of a class
(instance method).
public void setLength (double len)

Parameter variable declaration

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-18
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;
}

Examples: Rectangle.java, LengthDemo.java

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-19
public class Rectangle
{
private double length;
private double width;
public void setLength (double len)
{
length = len;
}
public void setWidth(double w)
{
width = w;
}
public double getLength()
{
return length;
}
public double getWidth()
{
return width;
}
public double getArea()
{
return length * width;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class LengthDemo
{
public static void main(String[] args)
{
Rectangle box = new Rectangle();

System.out.println("Sending the value 10.0 to "


+ "the setLength method.");
box.setLength(10.0);
System.out.println("Done.");
}
}
A Rectangle object
The box
variable holds length: 0.0
the address of address
the Rectangle width: 0.0
object.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Creating a Rectangle object

Rectangle box = new Rectangle ();


A Rectangle object
The box
variable holds length: 0.0
the address of address
the Rectangle width: 0.0
object.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-22
Calling the setLength Method

box.setLength(10.0);
The box A Rectangle object
variable holds
the address of length: 10.0
address
the width: 0.0
Rectangle
object.

This is the state of the box object after


the setLength method executes.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-23
Writing the getLength Method
/**
The getLength method returns a Rectangle
object's length.
@return The value in the length field.
*/
public double getLength()
{
return length;
}
Similarly, the setWidth and getWidth methods
can be created.
Examples: Rectangle.java, LengthWidthDemo.java

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-24
public class Rectangle
{
private double length;
private double width;
public void setLength (double len)
{
length = len;
}
public void setWidth(double w)
{
width = w;
}
public double getLength()
{
return length;
}
public double getWidth()
{
return width;
}
public double getArea()
{
return length * width;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class LengthWidthDemo
{
public static void main(String[] args)
{
Rectangle box = new Rectangle();

box.setLength(10.0);
box.setWidth(20.0);
System.out.println("The box's length is "
+ box.getLength());
System.out.println("The box's width is "
+ box.getWidth());
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Writing and Demonstrating the getArea
Method
/**
The getArea method returns a Rectangle
object's area.
@return The product of length times width.
*/
public double getArea()
{
return length * width;
}

Examples: Rectangle.java, RectangleDemo.java

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-27
public class Rectangle
{
private double length;
private double width;
public void setLength (double len)
{
length = len;
}
public void setWidth(double w)
{
width = w;
}
public double getLength()
{
return length;
}
public double getWidth()
{
return width;
}
public double getArea()
{
return length * width;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class RectangleDemo
{
public static void main(String[] args)
{
// Create a Rectangle object.
Rectangle box = new Rectangle();

// Set the length to 10 and width to 20.


box.setLength(10.0);
box.setWidth(20.0);

// Display the length, width, and area.


System.out.println("The box's length is "
+ box.getLength());
System.out.println("The box's width is "
+ box.getWidth());
System.out.println("The box's area is "
+ box.getArea());
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Accessor and Mutator Methods
• Because of the concept of data hiding, fields in a class
are private.
• The methods that retrieve the data of fields are called
accessors.
• The methods that modify the data of fields are called
mutators.
• Each field that the programmer wishes to be viewed by
other classes needs an accessor.
• Each field that the programmer wishes to be modified
by other classes needs a mutator.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-30
Accessors and Mutators
• For the Rectangle example, the accessors and
mutators are:
– setLength : Sets the value of the length field.
public void setLength(double len) …
– setWidth : Sets the value of the width field.
public void setLength(double w) …
– getLength : Returns the value of the length field.
public double getLength() …
– getWidth : Returns the value of the width field.
public double getWidth() …

• Other names for these methods are getters and setters.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-31
Data Hiding
• 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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Data Hiding
• Data hiding is important because classes are
typically used as components in large software
systems, involving a team of programmers.

• Data hiding helps enforce the integrity of an


object's internal data.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Stale Data
• Some data is the result of a calculation.
• Consider the area of a rectangle.
– length × width
• It would be impractical to use an area variable here.
• Data that requires the calculation of various factors has
the potential to become stale.
• To avoid stale data, it is best to calculate the value of
that data within a method rather than store it in a
variable.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-34
Stale Data
• 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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-35
UML Data Type and Parameter Notation
• UML diagrams are language independent.
• UML diagrams use an independent notation to show
return types, access modifiers, etc.

Access modifiers Rectangle


are denoted as:
+ public
- private - width : double

+ setWidth(w : double) : void

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-36
UML Data Type and Parameter Notation
• UML diagrams are language independent.
• UML diagrams use an independent notation to show
return types, access modifiers, etc.
Variable types are
Rectangle placed after the variable
name, separated by a
colon.
- width : double

+ setWidth(w : double) : void

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-37
UML Data Type and Parameter Notation
• UML diagrams are language independent.
• UML diagrams use an independent notation to show
return types, access modifiers, etc.

Method return types are


Rectangle placed after the method
declaration name,
separated by a colon.
- width : double

+ setWidth(w : double) : void

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-38
UML Data Type and Parameter Notation
• 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

+ setWidth(w : double) : void

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-39
Converting the UML Diagram to Code

• 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
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-40
Converting the UML Diagram to Code
public class Rectangle
The structure of the class can be {
compiled and tested without having private double width;
bodies for the methods. Just be sure to private double length;
put in dummy 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 }
- length : double public double getWidth()
{ return 0.0;
+ setWidth(w : double) : void }
public double getLength()
+ setLength(len : double): void { return 0.0;
+ getWidth() : double }
+ getLength() : double public double getArea()
+ getArea() : double { return 0.0;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-41
Converting the UML Diagram to Code
public class Rectangle
Once the class structure has been tested, {
private double width;
the method bodies can be written and
private double length;
tested.
public void setWidth(double w)
{ width = w;
}
Rectangle public void setLength(double len)
{ length = len;
- width : double }
- length : double public double getWidth()
{ return width;
}
+ setWidth(w : double) : void public double getLength()
+ setLength(len : double): void { return length;
+ getWidth() : double }
+ getLength() : double public double getArea()
{ return length * width;
+ getArea() : double }
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-42
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.
• There are tools that can help in formatting
layout to specific standards.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-43
Instance Fields and Methods
• 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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-44
Instance Fields and Methods
• 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();

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-45
public class RoomAreas
{
public static void main(String[] args)
{
double number, // To hold numeric input
totalArea; // The total area of all rooms
Scanner keyboard = new Scanner(System.in);
Rectangle kitchen = new Rectangle();
Rectangle bedroom = new Rectangle();
Rectangle den = new Rectangle();
System.out.print("What is the kitchen's length? ");
number = keyboard.nextDouble();
kitchen.setLength(number);
System.out.print("What is the kitchen's width? ");
number = keyboard.nextDouble();
kitchen.setWidth(number);
System.out.print("What is the bedroom's length? ");
number = keyboard.nextDouble();
bedroom.setLength(number);
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
System.out.print("What is the bedroom's width? ");
number = keyboard.nextDouble();
bedroom.setWidth(number);
System.out.print("What is the den's length? ");
number = keyboard.nextDouble();
den.setLength(number);
System.out.print("What is the den's width? ");
number = keyboard.nextDouble();
den.setWidth(number);
totalArea = kitchen.getArea() + bedroom.getArea()
+ den.getArea();
System.out.println("The total area of the rooms is "
+ totalArea);
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
States of Three Different Rectangle
Objects
The kitchen variable length: 10.0
holds the address of a address
Rectangle Object. width: 14.0

The bedroom variable length: 15.0


holds the address of a address
Rectangle Object. width: 12.0

The den variable


length: 20.0
holds the address of a address
Rectangle Object.
width: 30.0

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-48
// House.java // Rectangle.java
…. ……
….. …….
…. ……
Rectangle room = new Rectangle () ;
……
room.length = 10 ; // error since length is private
room.setLength (10) ; // OK, set length to 10

…….

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-49
• Rectangle.java
– this class defines Rectangle class.
– This is not a standalone program.
– It does not have a main method.
– It cannot be run by itself.
– Has internal (i.e. private) fields.
– Has methods that can be used by clients to access its
internal fields.
– All of these methods are NOT static.
– We call this type of class an instantiatable class.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-50
• House.java
– this is a client class of Rectangle.java, i.e. it creates
objects of type Rectangle using the new keyword.
– House.java does have a main method.
– Should not be able to directly access Rectangle’s
internal fields, but can use the public methods
provided by Rectangle class to access those fields in
a controlled manner.
– This class cannot have client classes, i.e. it is not
instantiatable.
– All of this class’s methods are static.
• Together, House.java, and all of the classes that
it is a client of, constitute a complete program.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-51
• Instantiatable classes
– like Rectangle.java
– Typically none of its methods are static.
– Usually does not have a main method (cannot run by itself).
– Has client classes (that create objects of it).
• Runnable classes
– like House.java
– Has a main method.
– Usually has all static methods.
– Does not have client classes
➢ This is all a bit of an over-simplification.
➢ We will see exceptions to all this in 161 and later courses.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-52
Constructors
• 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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-53
Constructors
• 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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-54
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;
}
Examples: Rectangle.java, ConstructorDemo.java

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-55
public class Rectangle
{
private double length;
private double width;
public Rectangle (double len, double w)
{
public class ConstructorDemo
length = len ;
{
width = w ;
public static void main(String[] args)
}
{
public void setLength (double len)
Rectangle box = new Rectangle(5.0, 15.0);
{
System.out.println("The box's length is " +
length = len;
box.getLength());
}
System.out.println("The box's width is " +
public void setWidth(double w)
box.getWidth());
{
width = w;
System.out.println("The box's area is “ +
}
box.getArea());
public double getLength()
}
{
}
return length;
}
public double getWidth()
{
return width;
}
public
©2016 double
Pearson getArea()
Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Constructors in UML
• In UML, the most common way constructors
are defined is:
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

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-57
The Die class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-58
import java.util.Random;
public class Die
{
private int sides; // Number of sides
private int value; // The die's value

public Die(int numSides)


{
sides = numSides;
roll();
}
public void roll()
{
// Create a Random object.
Random rand = new Random();

// Get a random value for the die.


value = rand.nextInt(sides) + 1;
}
public int getSides()
{
return sides;
}
public int getValue()
{
return value;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-59
public class DiceDemo
{
public static void main(String[] args)
{
final int DIE1_SIDES = 6; // Number of sides for die #1
final int DIE2_SIDES = 12; // Number of sides for die #2
final int MAX_ROLLS = 5; // Number of times to roll

Die die1 = new Die(DIE1_SIDES);


Die die2 = new Die(DIE2_SIDES);
System.out.println("This simulates the rolling of a " + DIE1_SIDES +
" sided die and a " + DIE2_SIDES + " sided die.");

System.out.println("Initial value of the dice:");


System.out.println(die1.getValue() + " " + die2.getValue());

System.out.println("Rolling the dice " + MAX_ROLLS + " times.");

for (int i = 0; i < MAX_ROLLS; i++)


{
die1.roll();
die2.roll();

System.out.println(die1.getValue() + " " + die2.getValue());


}
} Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
©2016 6-60
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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-61
The Default Constructor
• 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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-62
The Default Constructor
• 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

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-63
public class Rectangle
{
private double length;
private double width;
public Rectangle (double len, double w)
{
length = len ;
width = w ;
}
public void setLength (double len)
{
length = len;
}
public void setWidth(double w)
{
width = w;
}
public double getLength()
{
return length;
}
public double getWidth()
{
return width;
}
public
©2016 double
Pearson getArea()
Education, Inc. Upper Saddle River, NJ. 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;
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-65
The String Class Constructor
• 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:

String name = new String("Michael Long");

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-66
The String Class Constructor
• 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:

String name = "Michael Long";

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-67
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

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class DieArgument
{
public static void main(String[] args)
{
final int SIX_SIDES = 6;
final int TWENTY_SIDES = 20;

Die sixDie = new Die(SIX_SIDES);


Die twentyDie = new Die(TWENTY_SIDES);
S.o.println (sixDie.getValue ()) ;
S.o.println (sixDie.getValue ()) ;
rollDie(sixDie);
S.o.println (sixDie.getValue ()) ;
rollDie(twentyDie);
}
public static void rollDie(Die d)
{
// Display the number of sides.
System.out.println("Rolling a " + d.getSides() + " sided die.");

d.roll();
d = null ;
} Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
©2016 6-69
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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-70
Overloaded Method add
public int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
Public int add (int num1, int num2, int
num3)
{ return num1 + num2 + num3;
}
public String add (String str1, String str2)
{
String combined = str1 + str2;
©2016return combined;
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-71
Method Signature and Binding
• A method signature consists of the method’s name and the data
types of the method’s parameters, in the order that they appear.
The return type is not part of the signature.
Signatures of the
add(int, int)
add methods of
add(String, String)
previous slide
• The process of matching a method call with the correct method
is known as binding. The compiler uses the method signature to
determine which version of the overloaded method to bind the
call to.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-72
Rectangle Class Constructor Overload
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?

Rectangle box1 = new Rectangle();


Rectangle box2 = new Rectangle(5.0, 10.0);

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-73
Rectangle Class Constructor Overload
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?

Rectangle box1 = new Rectangle();


Rectangle box2 = new Rectangle(5.0, 10.0);

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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-74
The BankAccount Example
BankAccount.java BankAccount
AccountTest.java -balance:double

+BankAccount()

Overloaded Constructors +BankAccount(startBalance:double)


+BankAccount(strString:String)
+deposit(amount:double):void
Overloaded deposit methods
+deposit(str:String):void
+withdraw(amount:double):void
Overloaded withdraw methods
+withdraw(str:String):void
+setBalance(b:double):void
Overloaded setBalance methods
+setBalance(str:String):void
+getBalance():double

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-75
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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-76
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.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-77
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.*;

• The java.lang package is automatically made


available to any Java class.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-78
Some Java Standard Packages

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-79
Object Oriented Design
Finding Classes and Their Responsibilities

• Finding the classes


– Get written description of the problem domain
– Identify all nouns, each is a potential class
– Refine list to include only classes relevant to the
problem

• Identify the responsibilities


– Things a class is responsible for knowing
– Things a class is responsible for doing
– Refine list to include only classes relevant to the
problem

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-80
Object Oriented Design
Finding Classes and Their Responsibilities

– Identify the responsibilities


• Things a class is responsible for knowing
• Things a class is responsible for doing
• Refine list to include only classes relevant to the problem

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6-81

You might also like