SlideShare a Scribd company logo
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
C HA PT E R 3
A First Look
at Classes
and Objects
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Topics
Classes
More about Passing Arguments
Instance Fields and Methods
Constructors
A BankAccount Class
Classes, Variables, and Scope
Packages and import Statements
Focus on Object Oriented Design: Finding the
Classes and their Responsibilities
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Classes
In an object-oriented programming language,
like Java, you create programs that are made
of objects.
In software, an object has two capabilities:
An object can store data.
An object can perform operations.
The data stored in an object are commonly
called attributes or fields.
The operations that an object can perform
are called methods.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Strings as Objects
A primitive data type can only store
data, as it has no other built-in
capabilities.
An object can store data and perform
operations on that data.
In addition to storing strings, String objects
have numerous methods that perform
operations on the strings they hold.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Strings as Objects (cont’d)
• From chapter 2, we learned that a
reference variable contains the address
of an object.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Strings as Objects (cont’d)
The length() method of the String class
returns and integer value that is equal to the
length of the string.
int stringLength = cityName.length();
The variable stringLength will contain 10
after this statement since the string
"Charleston" has 10 characters.
Primitives can not have methods that can be
run whereas objects can.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Classes and Instances
Many objects can be created from a class.
Each object is independent of the others.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Classes and Instances
(cont’d)
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Classes and Instances
(cont’d)
Each instance of the String class
contains different data.
The instances are all share the same
design.
Each instance has all of the attributes
and methods that were defined in the
String class.
Classes are defined to represent a
single concept or service.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Access Modifiers
An access modifier is a Java key word
that indicates how a field or method can
be accessed.
There are three Java access modifiers:
public
private
protected
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Access Modifiers
public: This access modifier states that any
other class can access the resource.
private: This access modifier indicates that
only data within this class can access the
resource.
protected: This modifier indicates that only
classes in the current package or a class
lower in the class hierarchy can access this
resource.
These will be explained in greater detail later.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Access Modifiers
Classes that need to be used by other classes are
typically made public.
If there is more than one class in a file, only one may
be public and it must match the file name.
Class headers have a format:
AccessModifier class ClassName
{
Class Members
}
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Encapsulation
Classes should be as limited in scope as
needed to accomplish the goal.
Each class should contain all that is needed
for it to operate.
Enclosing the proper attributes and methods
inside a single class is called encapsulation.
Encapsulation ensures that the class is self-
contained.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Designing a Class
When designing a class, decisions
about the following must be made.
what data must be accounted for
what actions need to be performed
what data can be modified
what data needs to be accessible
any rules as to how data should be modified
Class design typically is done with the
aid of a Unified Modeling Language
(UML) diagram.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
UML Class Diagram
A UML class diagram is a graphical tool
that can aid in the design of a class.
The diagram has three main sections.
Class Name
Attributes
Methods
UML diagrams are easily converted
to Java class files. There will be more
about UML diagrams a little later.
The class name should concisely reflect what
the class represents.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Attributes
The data elements of a class define the
object to be instantiated from the class.
The attributes must be specific to the
class and define it completely.
Example: A rectangle is defined by
length
width
The attributes are then accessed by
methods within the class.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Data Hiding
Another aspect of encapsulation is the
concept of data hiding.
Classes should not only be self-contained
but they should be self-governing as well.
Classes use the private access modifier on
fields to hide them from other classes.
Classes need methods to allow access and
modification of the class’ data.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Methods
• The class’ methods define the actions that an
instance of the class can perform
• Methods headers have a format:
AccessModifier ReturnType
MethodName(Parameters)
{
//Method body.
}
• Methods that need to be used by other classes
should be made public.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Methods
• The attributes of a class might need to
be:
– changed
– accessed
– calculated
• The methods that change and access
attributes are called accessors and
mutators.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Accessors and Mutators
• 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.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Stale Data
• Some data is the result of a calculation.
• Consider the area of a rectangle.
– length times 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.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
UML Data Type and
Parameter Notation
• UML diagrams are language independent.
• UML diagrams use an independent notation
to show return types, access modifiers, etc.
Rectangle
- width : double
+ setWidth(w : double) : void
Access modifiers
are denoted as:
+ public
- private
# protected
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
UML Data Type and
Parameter Notation
• UML diagrams are language independent.
• UML diagrams use an independent notation
to show return types, access modifiers, etc.
Rectangle
- width : double
+ setWidth(w : double) : void
Variable types are
placed after the variable
name, separated by a
colon.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
UML Data Type and
Parameter Notation
• UML diagrams are language independent.
• UML diagrams use an independent notation
to show return types, access modifiers, etc.
Rectangle
- width : double
+ setWidth(w : double) : void
Method return types are
placed after the method
declaration name,
separated by a colon.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
UML Data Type and
Parameter Notation
• UML diagrams are language independent.
• UML diagrams use an independent notation
to show return types, access modifiers, etc.
Rectangle
- width : double
+ setWidth(w : double) : void
Method parameters
are shown inside the
parentheses using the
same notation as
variables.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
3-28
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.
ClassName
Attributes
Methods
class header
{
Attributes
Methods
}
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Converting the UML Diagram to Code
Rectangle
- width : double
- length : double
+ setWidth(w : double) : void
+ setLength(len : double): void
+ getWidth() : double
+ getLength() : double
+ getArea() : double
The structure of the class can be
compiled and tested without having
bodies for the methods. Just be sure to
put in dummy return values for methods
that have a return type other than void.
public class Rectangle
{
private double width;
private double length;
public void setWidth(double w)
{
}
public void setLength(double len)
{
}
public double getWidth()
{ return 0.0;
}
public double getLength()
{ return 0.0;
}
public double getArea()
{ return 0.0;
}
}
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Converting the UML Diagram to Code
Rectangle
- width : double
- length : double
+ setWidth(w : double) : void
+ setLength(len : double): void
+ getWidth() : double
+ getLength() : double
+ getArea() : double
Once the class structure has been tested,
the method bodies can be written and
tested.
public class Rectangle
{
private double width;
private double length;
public void setWidth(double w)
{ width = w;
}
public void setLength(double len)
{ length = len;
}
public double getWidth()
{ return width;
}
public double getLength()
{ return length;
}
public double getArea()
{ return length * width;
}
}
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Class Layout Conventions
The layout of a source code file can
vary by employer or instructor.
Generally the layout is:
Attributes are typically listed first
Methods are typically listed second
The main method is sometimes first, sometimes
last.
Accessors and mutators are typically grouped.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
A Driver Program
An application in Java is a collection of
classes that interact.
The class that starts the application
must have a main method.
This class can be used as a driver to
test the capabilities of other classes.
In the Rectangle class example, notice
that there was no main method.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
A Driver Program
public class RectangleDemo
{
public static void main(String[] args)
{
Rectangle r = new Rectangle();
r.setWidth(10);
r.setLength(10);
System.out.println("Width = "
+ r.getWidth());
System.out.println("Length = "
+ r.getLength());
System.out.println("Area = "
+ r.getArea());
}
}
This RectangleDemo class is a
Java application that uses the
Rectangle class.
public class Rectangle
{
private double width;
private double length;
public void setWidth(double w)
{ width = w;
}
public void setLength(double len)
{ length = len;
}
public double getWidth()
{ return width;
}
public double getLength()
{ return length;
}
public double getArea()
{ return length * width;
}
}
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Multiple Arguments
Methods can have multiple parameters.
The format for a multiple parameter method
is:
AccessModifier ReturnType MethodName(ParamType ParamName,
ParamType ParamName,
etc)
{
}
Parameters in methods are treated as local
variables within the method.
Example: MultipleArgs.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Arguments Passed By Value
In Java, all arguments to a method are
passed “by value”.
If the argument is a reference to an
object, it is the reference that is passed
to the method.
If the argument is a primitive, a copy of
the value is passed to the method.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Instance Fields and Methods
Instance fields and instance methods require
an object to be created in order to be used.
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 © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Constructors
Classes can have special methods
called constructors.
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 © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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.
Example: ConstructorDemo.java
Example: RoomConstructor.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Default Constructor
If a constructor is not defined, Java provides
a default constructor.
It sets all of the class’ numeric fields to 0.
It sets all of the class’ boolean fields to false.
It sets all of the class’ reference variables, the default
constructor sets them to the special value null.
The default constructor is a constructor with
no parameters.
Default constructors are used to initialize an
object in a default configuration.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Constructors in UML
In UML, the most common way constructors
are defined is:
Rectangle
- width : double
- length : double
+Rectangle(len:double, w:double)
+ setWidth(w : double) : void
+ setLength(len : double): void
+ getWidth() : double
+ getLength() : double
+ getArea() : double
Notice there is no
return type listed
for constructors.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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");
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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, Strings can
be created with a shorthand:
String name = "Michael Long";
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The BankAccount Example
BankAccount
- balance : double
- interestRate : double
- interest : double
+BankAccount(startBalance:double,
intRate :double):
+ deposit(amount : double) : void
+ withdrawl(amount : double: void
+ addInterest() : void
+ getBalance() : double
+ getInterest() : double
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Classes, Variables and Scope
The list below shows the scope of a variable
depending on where it is declared.
Inside a method:
Visible only within that method.
Called a local variable.
In a method parameter:
Called a parameter variable.
Same as a local variable
Visible only within that method.
Inside the class but not in a method:
Visible to all methods of the class.
Called an instance field.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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 © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Packages and import
Statements
A package is a group of related classes.
The classes in the Java API are organized into
packages.
For example, the Scanner class is in the java.util
package.
Many of the API classes must be imported before
they can be used. For example, the following
statement is required to import the Scanner class:
import java.util.Scanner; This statement appears at
the top of the program's
source code.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Packages and import
Statements
Explicit import Statements
An explicit import statement specifies a single
class:
import java.util.Scanner;
Wildcard import Statements
A wildcard import statement imports all of the
classes in a package:
import java.util.*;
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Packages and import
Statements
The java.lang package
Automatically imported into every Java
program.
Contains general classes such as String
and System.
You do not have to write an import
statement for the java.lang package.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Packages and import
Statements
You will use other packages as you learn more about Java.
Table 3-2 lists a few examples.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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

More Related Content

PDF
Inheritance
hccit
 
PPTX
Inheritance in Java
Ferdin Joe John Joseph PhD
 
PPT
Object Oriented Design
Sudarsun Santhiappan
 
PDF
Week08
hccit
 
PPT
Eo gaddis java_chapter_06_Classes and Objects
Gina Bullock
 
PPT
Lecture 5 inheritance
the_wumberlog
 
PPT
3. Data types and Variables
Nilesh Dalvi
 
Inheritance
hccit
 
Inheritance in Java
Ferdin Joe John Joseph PhD
 
Object Oriented Design
Sudarsun Santhiappan
 
Week08
hccit
 
Eo gaddis java_chapter_06_Classes and Objects
Gina Bullock
 
Lecture 5 inheritance
the_wumberlog
 
3. Data types and Variables
Nilesh Dalvi
 

What's hot (19)

PPTX
Chapter 6.4
sotlsoc
 
DOCX
OOP Concepets and UML Class Diagrams
Bhathiya Nuwan
 
PDF
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
PDF
Object Oriented Paradigm
Hüseyin Ergin
 
PPT
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
PPT
Java is an Object-Oriented Language
ale8819
 
PPTX
Object oriented programming Fundamental Concepts
Bharat Kalia
 
PPTX
Abstract class and Interface
Haris Bin Zahid
 
PPTX
Classes and Objects
Ferdin Joe John Joseph PhD
 
PPT
Object oriented programming (oop) cs304 power point slides lecture 01
Adil Kakakhel
 
PPTX
SKILLWISE - OOPS CONCEPT
Skillwise Group
 
PDF
Data types in Java
Play Store
 
PDF
Java programming -Object-Oriented Thinking- Inheritance
Jyothishmathi Institute of Technology and Science Karimnagar
 
PPTX
Lecture 1 uml with java implementation
the_wumberlog
 
PDF
OOP Inheritance
Anastasia Jakubow
 
PPTX
Object Oriented Programming Concepts
Abhigyan Singh Yadav
 
PDF
Lecture 1 - Objects and classes
Syed Afaq Shah MACS CP
 
PPSX
C#, OOP introduction and examples
agni_agbc
 
Chapter 6.4
sotlsoc
 
OOP Concepets and UML Class Diagrams
Bhathiya Nuwan
 
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
Object Oriented Paradigm
Hüseyin Ergin
 
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
Java is an Object-Oriented Language
ale8819
 
Object oriented programming Fundamental Concepts
Bharat Kalia
 
Abstract class and Interface
Haris Bin Zahid
 
Classes and Objects
Ferdin Joe John Joseph PhD
 
Object oriented programming (oop) cs304 power point slides lecture 01
Adil Kakakhel
 
SKILLWISE - OOPS CONCEPT
Skillwise Group
 
Data types in Java
Play Store
 
Java programming -Object-Oriented Thinking- Inheritance
Jyothishmathi Institute of Technology and Science Karimnagar
 
Lecture 1 uml with java implementation
the_wumberlog
 
OOP Inheritance
Anastasia Jakubow
 
Object Oriented Programming Concepts
Abhigyan Singh Yadav
 
Lecture 1 - Objects and classes
Syed Afaq Shah MACS CP
 
C#, OOP introduction and examples
agni_agbc
 
Ad

Similar to Eo gaddis java_chapter_03_5e (20)

PPT
Cso gaddis java_chapter6
RhettB
 
PPTX
Pi j2.3 objects
mcollison
 
PPTX
‫Object Oriented Programming_Lecture 3
Mahmoud Alfarra
 
PPT
Oops Concept Java
Kamlesh Singh
 
PPT
Cso gaddis java_chapter6
mlrbrown
 
PPTX
2 Object-oriented programghgrtrdwwe.pptx
RamaDalabeh
 
PPT
Lecture 2 classes i
the_wumberlog
 
PPTX
Object-oriented programming
Neelesh Shukla
 
PPTX
Chap5java5th
Asfand Hassan
 
PPT
OO Development 4 - Object Concepts
Randy Connolly
 
PPTX
Chapter 4 Writing Classes
DanWooster1
 
PPT
10slide.ppt
MohammedNouh7
 
PPT
Class & Object - Intro
PRN USM
 
PPT
OOP Principles
Upender Upr
 
PPT
encapsulation and abstraction
ALIZAPARVIN
 
PPT
Java căn bản - Chapter4
Vince Vo
 
PPT
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
PPTX
Object oriented concepts
Gousalya Ramachandran
 
PDF
Introduction to java and oop
baabtra.com - No. 1 supplier of quality freshers
 
PPT
1207028 634528828886611250
Akhil Nama
 
Cso gaddis java_chapter6
RhettB
 
Pi j2.3 objects
mcollison
 
‫Object Oriented Programming_Lecture 3
Mahmoud Alfarra
 
Oops Concept Java
Kamlesh Singh
 
Cso gaddis java_chapter6
mlrbrown
 
2 Object-oriented programghgrtrdwwe.pptx
RamaDalabeh
 
Lecture 2 classes i
the_wumberlog
 
Object-oriented programming
Neelesh Shukla
 
Chap5java5th
Asfand Hassan
 
OO Development 4 - Object Concepts
Randy Connolly
 
Chapter 4 Writing Classes
DanWooster1
 
10slide.ppt
MohammedNouh7
 
Class & Object - Intro
PRN USM
 
OOP Principles
Upender Upr
 
encapsulation and abstraction
ALIZAPARVIN
 
Java căn bản - Chapter4
Vince Vo
 
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Object oriented concepts
Gousalya Ramachandran
 
1207028 634528828886611250
Akhil Nama
 
Ad

More from Gina Bullock (20)

PPT
Eo gaddis java_chapter_10_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_14_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_12_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_11_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_09_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_08_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_06_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_05_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_04_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_01_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_06_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_10_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_07_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_01_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_16_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_14_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_13_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_12_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_11_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_09_5e
Gina Bullock
 
Eo gaddis java_chapter_10_5e
Gina Bullock
 
Eo gaddis java_chapter_14_5e
Gina Bullock
 
Eo gaddis java_chapter_12_5e
Gina Bullock
 
Eo gaddis java_chapter_11_5e
Gina Bullock
 
Eo gaddis java_chapter_09_5e
Gina Bullock
 
Eo gaddis java_chapter_08_5e
Gina Bullock
 
Eo gaddis java_chapter_06_5e
Gina Bullock
 
Eo gaddis java_chapter_05_5e
Gina Bullock
 
Eo gaddis java_chapter_04_5e
Gina Bullock
 
Eo gaddis java_chapter_01_5e
Gina Bullock
 
Eo gaddis java_chapter_06_5e
Gina Bullock
 
Eo gaddis java_chapter_10_5e
Gina Bullock
 
Eo gaddis java_chapter_07_5e
Gina Bullock
 
Eo gaddis java_chapter_01_5e
Gina Bullock
 
Eo gaddis java_chapter_16_5e
Gina Bullock
 
Eo gaddis java_chapter_14_5e
Gina Bullock
 
Eo gaddis java_chapter_13_5e
Gina Bullock
 
Eo gaddis java_chapter_12_5e
Gina Bullock
 
Eo gaddis java_chapter_11_5e
Gina Bullock
 
Eo gaddis java_chapter_09_5e
Gina Bullock
 

Recently uploaded (20)

PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PPTX
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PPTX
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
PPTX
CDH. pptx
AneetaSharma15
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Basics and rules of probability with real-life uses
ravatkaran694
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
CDH. pptx
AneetaSharma15
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 

Eo gaddis java_chapter_03_5e

  • 1. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C HA PT E R 3 A First Look at Classes and Objects
  • 2. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics Classes More about Passing Arguments Instance Fields and Methods Constructors A BankAccount Class Classes, Variables, and Scope Packages and import Statements Focus on Object Oriented Design: Finding the Classes and their Responsibilities
  • 3. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Classes In an object-oriented programming language, like Java, you create programs that are made of objects. In software, an object has two capabilities: An object can store data. An object can perform operations. The data stored in an object are commonly called attributes or fields. The operations that an object can perform are called methods.
  • 4. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Strings as Objects A primitive data type can only store data, as it has no other built-in capabilities. An object can store data and perform operations on that data. In addition to storing strings, String objects have numerous methods that perform operations on the strings they hold.
  • 5. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Strings as Objects (cont’d) • From chapter 2, we learned that a reference variable contains the address of an object.
  • 6. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Strings as Objects (cont’d) The length() method of the String class returns and integer value that is equal to the length of the string. int stringLength = cityName.length(); The variable stringLength will contain 10 after this statement since the string "Charleston" has 10 characters. Primitives can not have methods that can be run whereas objects can.
  • 7. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Classes and Instances Many objects can be created from a class. Each object is independent of the others.
  • 8. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Classes and Instances (cont’d)
  • 9. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Classes and Instances (cont’d) Each instance of the String class contains different data. The instances are all share the same design. Each instance has all of the attributes and methods that were defined in the String class. Classes are defined to represent a single concept or service.
  • 10. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Access Modifiers An access modifier is a Java key word that indicates how a field or method can be accessed. There are three Java access modifiers: public private protected
  • 11. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Access Modifiers public: This access modifier states that any other class can access the resource. private: This access modifier indicates that only data within this class can access the resource. protected: This modifier indicates that only classes in the current package or a class lower in the class hierarchy can access this resource. These will be explained in greater detail later.
  • 12. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Access Modifiers Classes that need to be used by other classes are typically made public. If there is more than one class in a file, only one may be public and it must match the file name. Class headers have a format: AccessModifier class ClassName { Class Members }
  • 13. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Encapsulation Classes should be as limited in scope as needed to accomplish the goal. Each class should contain all that is needed for it to operate. Enclosing the proper attributes and methods inside a single class is called encapsulation. Encapsulation ensures that the class is self- contained.
  • 14. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Designing a Class When designing a class, decisions about the following must be made. what data must be accounted for what actions need to be performed what data can be modified what data needs to be accessible any rules as to how data should be modified Class design typically is done with the aid of a Unified Modeling Language (UML) diagram.
  • 15. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley UML Class Diagram A UML class diagram is a graphical tool that can aid in the design of a class. The diagram has three main sections. Class Name Attributes Methods UML diagrams are easily converted to Java class files. There will be more about UML diagrams a little later. The class name should concisely reflect what the class represents.
  • 16. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Attributes The data elements of a class define the object to be instantiated from the class. The attributes must be specific to the class and define it completely. Example: A rectangle is defined by length width The attributes are then accessed by methods within the class.
  • 17. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Hiding Another aspect of encapsulation is the concept of data hiding. Classes should not only be self-contained but they should be self-governing as well. Classes use the private access modifier on fields to hide them from other classes. Classes need methods to allow access and modification of the class’ data.
  • 18. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Methods • The class’ methods define the actions that an instance of the class can perform • Methods headers have a format: AccessModifier ReturnType MethodName(Parameters) { //Method body. } • Methods that need to be used by other classes should be made public.
  • 19. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Methods • The attributes of a class might need to be: – changed – accessed – calculated • The methods that change and access attributes are called accessors and mutators.
  • 20. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Accessors and Mutators • 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.
  • 21. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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.
  • 22. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Stale Data • Some data is the result of a calculation. • Consider the area of a rectangle. – length times 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.
  • 23. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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.
  • 24. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley UML Data Type and Parameter Notation • UML diagrams are language independent. • UML diagrams use an independent notation to show return types, access modifiers, etc. Rectangle - width : double + setWidth(w : double) : void Access modifiers are denoted as: + public - private # protected
  • 25. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley UML Data Type and Parameter Notation • UML diagrams are language independent. • UML diagrams use an independent notation to show return types, access modifiers, etc. Rectangle - width : double + setWidth(w : double) : void Variable types are placed after the variable name, separated by a colon.
  • 26. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley UML Data Type and Parameter Notation • UML diagrams are language independent. • UML diagrams use an independent notation to show return types, access modifiers, etc. Rectangle - width : double + setWidth(w : double) : void Method return types are placed after the method declaration name, separated by a colon.
  • 27. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley UML Data Type and Parameter Notation • UML diagrams are language independent. • UML diagrams use an independent notation to show return types, access modifiers, etc. Rectangle - width : double + setWidth(w : double) : void Method parameters are shown inside the parentheses using the same notation as variables.
  • 28. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-28 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. ClassName Attributes Methods class header { Attributes Methods }
  • 29. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Converting the UML Diagram to Code Rectangle - width : double - length : double + setWidth(w : double) : void + setLength(len : double): void + getWidth() : double + getLength() : double + getArea() : double The structure of the class can be compiled and tested without having bodies for the methods. Just be sure to put in dummy return values for methods that have a return type other than void. public class Rectangle { private double width; private double length; public void setWidth(double w) { } public void setLength(double len) { } public double getWidth() { return 0.0; } public double getLength() { return 0.0; } public double getArea() { return 0.0; } }
  • 30. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Converting the UML Diagram to Code Rectangle - width : double - length : double + setWidth(w : double) : void + setLength(len : double): void + getWidth() : double + getLength() : double + getArea() : double Once the class structure has been tested, the method bodies can be written and tested. public class Rectangle { private double width; private double length; public void setWidth(double w) { width = w; } public void setLength(double len) { length = len; } public double getWidth() { return width; } public double getLength() { return length; } public double getArea() { return length * width; } }
  • 31. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Class Layout Conventions The layout of a source code file can vary by employer or instructor. Generally the layout is: Attributes are typically listed first Methods are typically listed second The main method is sometimes first, sometimes last. Accessors and mutators are typically grouped.
  • 32. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Driver Program An application in Java is a collection of classes that interact. The class that starts the application must have a main method. This class can be used as a driver to test the capabilities of other classes. In the Rectangle class example, notice that there was no main method.
  • 33. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Driver Program public class RectangleDemo { public static void main(String[] args) { Rectangle r = new Rectangle(); r.setWidth(10); r.setLength(10); System.out.println("Width = " + r.getWidth()); System.out.println("Length = " + r.getLength()); System.out.println("Area = " + r.getArea()); } } This RectangleDemo class is a Java application that uses the Rectangle class. public class Rectangle { private double width; private double length; public void setWidth(double w) { width = w; } public void setLength(double len) { length = len; } public double getWidth() { return width; } public double getLength() { return length; } public double getArea() { return length * width; } }
  • 34. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Multiple Arguments Methods can have multiple parameters. The format for a multiple parameter method is: AccessModifier ReturnType MethodName(ParamType ParamName, ParamType ParamName, etc) { } Parameters in methods are treated as local variables within the method. Example: MultipleArgs.java
  • 35. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arguments Passed By Value In Java, all arguments to a method are passed “by value”. If the argument is a reference to an object, it is the reference that is passed to the method. If the argument is a primitive, a copy of the value is passed to the method.
  • 36. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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.
  • 37. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Instance Fields and Methods Instance fields and instance methods require an object to be created in order to be used. 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();
  • 38. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Constructors Classes can have special methods called constructors. Constructors are used to perform operations at the time an object is created. Constructors typically initialize instance fields and perform other object initialization tasks.
  • 39. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. Example: ConstructorDemo.java Example: RoomConstructor.java
  • 40. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Default Constructor If a constructor is not defined, Java provides a default constructor. It sets all of the class’ numeric fields to 0. It sets all of the class’ boolean fields to false. It sets all of the class’ reference variables, the default constructor sets them to the special value null. The default constructor is a constructor with no parameters. Default constructors are used to initialize an object in a default configuration.
  • 41. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Constructors in UML In UML, the most common way constructors are defined is: Rectangle - width : double - length : double +Rectangle(len:double, w:double) + setWidth(w : double) : void + setLength(len : double): void + getWidth() : double + getLength() : double + getArea() : double Notice there is no return type listed for constructors.
  • 42. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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");
  • 43. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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, Strings can be created with a shorthand: String name = "Michael Long";
  • 44. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The BankAccount Example BankAccount - balance : double - interestRate : double - interest : double +BankAccount(startBalance:double, intRate :double): + deposit(amount : double) : void + withdrawl(amount : double: void + addInterest() : void + getBalance() : double + getInterest() : double
  • 45. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Classes, Variables and Scope The list below shows the scope of a variable depending on where it is declared. Inside a method: Visible only within that method. Called a local variable. In a method parameter: Called a parameter variable. Same as a local variable Visible only within that method. Inside the class but not in a method: Visible to all methods of the class. Called an instance field.
  • 46. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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.
  • 47. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Packages and import Statements A package is a group of related classes. The classes in the Java API are organized into packages. For example, the Scanner class is in the java.util package. Many of the API classes must be imported before they can be used. For example, the following statement is required to import the Scanner class: import java.util.Scanner; This statement appears at the top of the program's source code.
  • 48. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Packages and import Statements Explicit import Statements An explicit import statement specifies a single class: import java.util.Scanner; Wildcard import Statements A wildcard import statement imports all of the classes in a package: import java.util.*;
  • 49. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Packages and import Statements The java.lang package Automatically imported into every Java program. Contains general classes such as String and System. You do not have to write an import statement for the java.lang package.
  • 50. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Packages and import Statements You will use other packages as you learn more about Java. Table 3-2 lists a few examples.
  • 51. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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
  • 52. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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