0% found this document useful (0 votes)
41 views52 pages

Lesson 5 A First Look at Classes

Uploaded by

Fethulmubin
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)
41 views52 pages

Lesson 5 A First Look at Classes

Uploaded by

Fethulmubin
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/ 52

Chapter 6 | A First Look at Classes

Chapter 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
6.1 Objects and Classes (1 of 5)

• 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.
• 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
6.1 Objects and Classes (2 of 5)
• 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.
• 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.
6.1 Objects and Classes (3 of 5)

Example:
6.1 Objects and Classes (4 of 5)

Example:
6.1 Objects and Classes (5 of 5)

• 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
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.
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.
UML Diagram
• Unified Modeling Language (UML) provides a set of
standard diagrams for graphically depicting object-oriented
systems.
UML Diagram for Rectangle Class
Writing the Code for the Rectangle Class

Class Fields

Member methods


• The public access specifier in “public class Rectangle” indicates that the class will be
publicly available to code that is written outside the Rectangle.java file. Almost
all of the classes that we write in this book are public.

• By using the private access modifier, a class can hide its data from code
outside the class to protect the data from accidental corruption.

• A class usually has private fields, and public methods that access those fields.
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.
Header for the setLength Method
Creating a Rectangle Object

The box variable


holds the address
of the Rectangle
object.
Calling the setLength Method

The box variable


holds the address
of the Rectangle
object.

This is the state of the box object after the setLength


method executes
Writing the getLength Method

Similarly, the setWidth and getWidth methods can be


created.
Examples: Rectangle.java, LengthWidthDemo.java
Writing and Demonstrating the getArea Method

Examples: Rectangle.java, RectangleDemo.java


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.
Accessors and Mutators
• For the Rectangle example, the accessors and mutators are:
– setLength : Sets the value of the length field.

– setWidth : Sets the value of the width field.

– getLength : Returns the value of the length field.

– getWidth : Returns the value of the width field.

• Other names for these methods are getters and setters.


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.
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.
• Data hiding helps enforce the integrity of an object’s
internal data.
Stale Data (1 of 2)

• 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.
Stale Data (2 of 2)
• Rather than use an area variable in a Rectangle class:

• 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.
UML Data Type and Parameter Notation

• UML diagrams are language independent.


• UML diagrams use an independent notation to show return types,
access modifiers, etc.
Converting the UML Diagram to Code (1 of 2)

• 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.
Converting the UML Diagram to Code (2 of 2)
Once the class structure has been tested, the method bodies
can be written and tested.
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.
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.
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.
States of Three Different Rectangle Objects

The kitchen variable holds


the address of a Rectangle
Object.

The bedroom variable holds


the address of a Rectangle
Object.

The den variable holds the


address of a Rectangle
Object.
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.
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.
Constructor for Rectangle Class

Examples: Rectangle.java, ConstructorDemo.java


Constructors in UML

• In UML, the most common way constructors are defined


is:
Uninitialized Local Reference Variables
• Reference variables can be declared without being initialized.

• 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 will now reference a Rectangle object of length 7.0 and


width 14.0.
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.
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
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
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
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.
Overloaded Method add
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.

• 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.
Exercise

• 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?
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.
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.
Packages and import Statements

• Classes in the Java API are organized into packages.


• Explicit and Wildcard import statements
– Explicit imports name a specific class

– Wildcard imports name a package, followed by an *

• The java.lang package is automatically made
available to any Java class.
Some Java Standard Packages
Table 6-2 A few of the standard Java packages

Package Description
java.applet Provides the classes necessary to create an applet.
java.awt Provides classes for the Abstract Windowing Toolkit. These classes are used in
drawing images and creating graphical user interfaces.
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.
java.security Provides classes that implement security features.
java.sql Provides classes for accessing databases using structured query language.
java.text Provides various classes for formatting text.
java.util Provides various utility classes.
javax.swing Provides classes for creating graphical user interfaces.
Exercise
/** /**
The Circle class stores data about a circle The getRadius method returns the circle's radius.
for the Circle Class programming challenge. @return The radius.
*/ */
public class Circle
{ public double getRadius()
private final double PI = 3.14159; // Constant for pi {
private double radius; // The circle's radius return radius;
}
/** /**
This constructor initializes the object with The area method returns the circle's area.
a radius of 0.0. @return The area of the circle.
*/ */

public Circle() public double area()


{ {
radius = 0.0; return PI * radius * radius;
} }

/** /**
The constructor initializes the object with The diameter method returns the circle's diameter.
a specified radius. @return The diamter of the circle.
@param r The circle's radius. */
*/
public double diameter()
public Circle(double r) {
{ return radius * 2;
radius = r; }
} /**
The circumference method returns the
/** circle's circumference.
The setRadius method sets the circle's radius. @return The circumference of the circle.
@param r The radius. */
*/ public double circumference()
public void setRadius(double r) {
{ return 2 * PI * radius;
radius = r; }
} }
Demo Class import java.util.Scanner;

/**
This program demonstrates a solution to the
Circle Class programming challenge.
*/

public class CircleDemo


{
public static void main(String[] args)
{
double radius; // The radius of a circle

// Create a Scanner object for keyboard input.


Scanner keyboard = new Scanner(System.in);

// Get the radius of a circle.


System.out.print("Enter the radius of a circle: ");
radius = keyboard.nextDouble();

// Create a Circle object.


Circle c = new Circle(radius);

// Display geometric info about the circle.


System.out.printf("The circle's area is %,.2f\n", c.area());
System.out.printf("The circle's diameter is %,.2f\n", c.diameter());
System.out.printf("The circle's circumference is %,.2f\n", c.circumference());
}
}
Exercise

You might also like