SlideShare a Scribd company logo
Chapter 4
Writing Classes
– Part 2
Java Software Solutions
Foundations of Program Design
9th Edition
John Lewis
William Loftus
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Key Concept
• The heart of object-oriented
programming is defining classes that
represent objects with well-defined
state and behavior.
Writing
Classes
The programs we’ve written in previous
examples have used classes defined in the Java
API
Now we will begin to design programs that rely
on classes that we write ourselves
The class that contains the main method is just
the starting point of a program
True object-oriented programming is based on
defining classes that represent objects with
well-defined characteristics and functionality
Examples of
Classes
Classes and
Objects
Recall from our overview of objects in Chapter 1 that
an object has state and behavior
Consider a six-sided die
(singular of dice)
Its state can be defined as
which face is showing
Its primary behavior is that it
can be rolled
We represent a die by
designing a class called Die
that models this state and
behavior
The class serves as the
blueprint for a die object
We can then instantiate as many die objects as we
need for any particular program
Classes
• A class can contain data declarations and method
declarations
int size, weight;
char category;
Data declarations
Method declarations
Classes
The values of the data define the state of
an object created from the class
The functionality of the methods define
the behaviors of the object
For our Die class, we might declare an
integer called faceValue that represents
the current value showing on the face
One of the methods would “roll” the die
by setting faceValue to a random number
between one and six
Classes
We’ll want to design the Die class so that
it is a versatile and reusable resource
Any given program will probably not use
all operations of a given class
See RollingDice.java
See Die.java
//********************************************************************
// RollingDice.java Author: Lewis/Loftus
//
// Demonstrates the creation and use of a user-defined class.
//********************************************************************
public class RollingDice
{
//-----------------------------------------------------------------
// Creates two Die objects and rolls them several times.
//-----------------------------------------------------------------
public static void main(String[] args)
{
Die die1, die2;
int sum;
die1 = new Die();
die2 = new Die();
die1.roll();
die2.roll();
System.out.println("Die One: " + die1 + ", Die Two: " + die2);
continue
continue
die1.roll();
die2.setFaceValue(4);
System.out.println("Die One: " + die1 + ", Die Two: " + die2);
sum = die1.getFaceValue() + die2.getFaceValue();
System.out.println("Sum: " + sum);
sum = die1.roll() + die2.roll();
System.out.println("Die One: " + die1 + ", Die Two: " + die2);
System.out.println("New sum: " + sum);
}
}
continue
die1.roll();
die2.setFaceValue(4);
System.out.println("Die One: " + die1 + ", Die Two: " + die2);
sum = die1.getFaceValue() + die2.getFaceValue();
System.out.println("Sum: " + sum);
sum = die1.roll() + die2.roll();
System.out.println("Die One: " + die1 + ", Die Two: " + die2);
System.out.println("New sum: " + sum);
}
}
Sample Run
Die One: 5, Die Two: 2
Die One: 1, Die Two: 4
Sum: 5
Die One: 4, Die Two: 2
New sum: 6
//********************************************************************
// Die.java Author: Lewis/Loftus
//
// Represents one die (singular of dice) with faces showing values
// between 1 and 6.
//********************************************************************
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
//-----------------------------------------------------------------
// Constructor: Sets the initial face value.
//-----------------------------------------------------------------
public Die()
{
faceValue = 1;
}
continue
continue
//-----------------------------------------------------------------
// Rolls the die and returns the result.
//-----------------------------------------------------------------
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
//-----------------------------------------------------------------
// Face value mutator.
//-----------------------------------------------------------------
public void setFaceValue(int value)
{
faceValue = value;
}
//-----------------------------------------------------------------
// Face value accessor.
//-----------------------------------------------------------------
public int getFaceValue()
{
return faceValue;
}
continue
continue
//-----------------------------------------------------------------
// Returns a string representation of this die.
//-----------------------------------------------------------------
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
The Die Class
The Die class
contains two data
values
a constant MAX that
represents the
maximum face value
an integer faceValue
that represents the
current face value
The roll method uses the random
method of the Math class to
determine a new face value
There are also methods to
explicitly set and retrieve the
current face value at any time
The toString
Method
It's good practice to define a
toString method for a class
The toString method returns a
character string that represents
the object in some way
It is called automatically when
an object is concatenated to a
string or when it is passed to
the println method
It's also convenient for
debugging problems
Constructors
As mentioned previously, a constructor is
used to set up an object when it is initially
created
A constructor has the same name as the
class
The Die constructor is used to set the
initial face value of each new die object to
one
We examine constructors in more detail
later in this chapter
Key Concept
• The scope of a variable, which
determines where it can be referenced,
depends on where it is declared.
Data Scope
The scope of data is the area in a program in which that data
can be referenced (used)
Data declared at the class level can be referenced by all
methods in that class
Data declared within a method can be used only in that
method
Data declared within a method is called local data
In the Die class, the variable result is declared inside the
toString method -- it is local to that method and cannot be
referenced anywhere else
Instance Data
A variable declared at the class level (such as
faceValue) is called instance data
Each instance (object) has its own instance variable
A class declares the type of the data, but it does not
reserve memory space for it
Each time a Die object is created, a new faceValue
variable is created as well
The objects of a class share the method definitions,
but each object has its own data space
That's the only way two objects can have different
states
Instance Data
• We can depict the two Die objects from the
RollingDice program as follows:
die1 5faceValue
die2 2faceValue
Each object maintains its own faceValue
variable, and thus its own state
Key Concept
• A UML class diagram helps us visualize
the contents of and relationships
among the classes of a program.
UML
Diagrams
UML stands for the Unified Modeling Language
UML diagrams show relationships among classes and
objects
A UML class diagram consists of one or more classes,
each with sections for the class name, attributes (data),
and operations (methods)
Lines between classes represent associations
A dotted arrow shows that one class uses the other
(calls its methods)
UML Class Diagrams
• A UML class diagram for the RollingDice program:
RollingDice
main (args : String[]) : void
Die
faceValue : int
roll() : int
setFaceValue (int value) : void
getFaceValue() : int
toString() : String
Ad

More Related Content

What's hot (20)

Java Chapter 04 - Writing Classes: part 3
Java Chapter 04 - Writing Classes: part 3 Java Chapter 04 - Writing Classes: part 3
Java Chapter 04 - Writing Classes: part 3
DanWooster1
 
SAP ABAP using OOPS - JH Softech
SAP ABAP using OOPS - JH SoftechSAP ABAP using OOPS - JH Softech
SAP ABAP using OOPS - JH Softech
Vikram P Madduri
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
dplunkett
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
Harsh Patel
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
Aashiq Kuchey
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
Abishek Purushothaman
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
Maryo Manjaruni
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
Prarabdh Garg
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
Pushpendra Tyagi
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
2- Introduction to java II
2-  Introduction to java II2-  Introduction to java II
2- Introduction to java II
Ghadeer AlHasan
 
5- Overriding and Abstraction In Java
5- Overriding and Abstraction In Java5- Overriding and Abstraction In Java
5- Overriding and Abstraction In Java
Ghadeer AlHasan
 
Abap Inicio
Abap InicioAbap Inicio
Abap Inicio
unifor
 
Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3
Ricardo Quintero
 
Java interface
Java interfaceJava interface
Java interface
Md. Tanvir Hossain
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
 
Java Chapter 04 - Writing Classes: part 3
Java Chapter 04 - Writing Classes: part 3 Java Chapter 04 - Writing Classes: part 3
Java Chapter 04 - Writing Classes: part 3
DanWooster1
 
SAP ABAP using OOPS - JH Softech
SAP ABAP using OOPS - JH SoftechSAP ABAP using OOPS - JH Softech
SAP ABAP using OOPS - JH Softech
Vikram P Madduri
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
dplunkett
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
Harsh Patel
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
Aashiq Kuchey
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
Maryo Manjaruni
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
Pushpendra Tyagi
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
2- Introduction to java II
2-  Introduction to java II2-  Introduction to java II
2- Introduction to java II
Ghadeer AlHasan
 
5- Overriding and Abstraction In Java
5- Overriding and Abstraction In Java5- Overriding and Abstraction In Java
5- Overriding and Abstraction In Java
Ghadeer AlHasan
 
Abap Inicio
Abap InicioAbap Inicio
Abap Inicio
unifor
 
Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3
Ricardo Quintero
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
 

Similar to Java Chapter 04 - Writing Classes: part 2 (20)

Object & classes
Object & classes Object & classes
Object & classes
Paresh Parmar
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
sandy14234
 
java tr.docx
java tr.docxjava tr.docx
java tr.docx
harishkuna4
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
Khaled Anaqwa
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
farhan amjad
 
Unit i
Unit iUnit i
Unit i
snehaarao19
 
oops-1
oops-1oops-1
oops-1
snehaarao19
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
VasanthiMuniasamy2
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
Mohammad Shaker
 
Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1
bharath yelugula
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
Indu65
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 
Object oriented design-UNIT V
Object oriented design-UNIT VObject oriented design-UNIT V
Object oriented design-UNIT V
Azhar Shaik
 
Java-Variables_about_different_Scope.ppt
Java-Variables_about_different_Scope.pptJava-Variables_about_different_Scope.ppt
Java-Variables_about_different_Scope.ppt
JyothiAmpally
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
Object Oriented Principle’s
Object Oriented Principle’sObject Oriented Principle’s
Object Oriented Principle’s
vivek p s
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
Khaled Anaqwa
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
farhan amjad
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
Mohammad Shaker
 
Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1
bharath yelugula
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
Indu65
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 
Object oriented design-UNIT V
Object oriented design-UNIT VObject oriented design-UNIT V
Object oriented design-UNIT V
Azhar Shaik
 
Java-Variables_about_different_Scope.ppt
Java-Variables_about_different_Scope.pptJava-Variables_about_different_Scope.ppt
Java-Variables_about_different_Scope.ppt
JyothiAmpally
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
Object Oriented Principle’s
Object Oriented Principle’sObject Oriented Principle’s
Object Oriented Principle’s
vivek p s
 
Ad

More from DanWooster1 (20)

Upstate CSCI 540 Agile Development
Upstate CSCI 540 Agile DevelopmentUpstate CSCI 540 Agile Development
Upstate CSCI 540 Agile Development
DanWooster1
 
Upstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testingUpstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testing
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1
DanWooster1
 
Upstate CSCI 525 Data Mining Chapter 3
Upstate CSCI 525 Data Mining Chapter 3Upstate CSCI 525 Data Mining Chapter 3
Upstate CSCI 525 Data Mining Chapter 3
DanWooster1
 
Upstate CSCI 525 Data Mining Chapter 2
Upstate CSCI 525 Data Mining Chapter 2Upstate CSCI 525 Data Mining Chapter 2
Upstate CSCI 525 Data Mining Chapter 2
DanWooster1
 
Upstate CSCI 525 Data Mining Chapter 1
Upstate CSCI 525 Data Mining Chapter 1Upstate CSCI 525 Data Mining Chapter 1
Upstate CSCI 525 Data Mining Chapter 1
DanWooster1
 
Upstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - ArraysUpstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - Arrays
DanWooster1
 
Upstate CSCI 200 Java Chapter 7 - OOP
Upstate CSCI 200 Java Chapter 7 - OOPUpstate CSCI 200 Java Chapter 7 - OOP
Upstate CSCI 200 Java Chapter 7 - OOP
DanWooster1
 
CSCI 200 Java Chapter 03 Using Classes
CSCI 200 Java Chapter 03 Using ClassesCSCI 200 Java Chapter 03 Using Classes
CSCI 200 Java Chapter 03 Using Classes
DanWooster1
 
CSCI 200 Java Chapter 02 Data & Expressions
CSCI 200 Java Chapter 02 Data & ExpressionsCSCI 200 Java Chapter 02 Data & Expressions
CSCI 200 Java Chapter 02 Data & Expressions
DanWooster1
 
CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01
DanWooster1
 
CSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook SlidesCSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook Slides
DanWooster1
 
Chapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loopsChapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loops
DanWooster1
 
Upstate CSCI 450 jQuery
Upstate CSCI 450 jQueryUpstate CSCI 450 jQuery
Upstate CSCI 450 jQuery
DanWooster1
 
Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13
DanWooster1
 
Upstate CSCI 540 Agile Development
Upstate CSCI 540 Agile DevelopmentUpstate CSCI 540 Agile Development
Upstate CSCI 540 Agile Development
DanWooster1
 
Upstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testingUpstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testing
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2
DanWooster1
 
Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1
DanWooster1
 
Upstate CSCI 525 Data Mining Chapter 3
Upstate CSCI 525 Data Mining Chapter 3Upstate CSCI 525 Data Mining Chapter 3
Upstate CSCI 525 Data Mining Chapter 3
DanWooster1
 
Upstate CSCI 525 Data Mining Chapter 2
Upstate CSCI 525 Data Mining Chapter 2Upstate CSCI 525 Data Mining Chapter 2
Upstate CSCI 525 Data Mining Chapter 2
DanWooster1
 
Upstate CSCI 525 Data Mining Chapter 1
Upstate CSCI 525 Data Mining Chapter 1Upstate CSCI 525 Data Mining Chapter 1
Upstate CSCI 525 Data Mining Chapter 1
DanWooster1
 
Upstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - ArraysUpstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - Arrays
DanWooster1
 
Upstate CSCI 200 Java Chapter 7 - OOP
Upstate CSCI 200 Java Chapter 7 - OOPUpstate CSCI 200 Java Chapter 7 - OOP
Upstate CSCI 200 Java Chapter 7 - OOP
DanWooster1
 
CSCI 200 Java Chapter 03 Using Classes
CSCI 200 Java Chapter 03 Using ClassesCSCI 200 Java Chapter 03 Using Classes
CSCI 200 Java Chapter 03 Using Classes
DanWooster1
 
CSCI 200 Java Chapter 02 Data & Expressions
CSCI 200 Java Chapter 02 Data & ExpressionsCSCI 200 Java Chapter 02 Data & Expressions
CSCI 200 Java Chapter 02 Data & Expressions
DanWooster1
 
CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01
DanWooster1
 
CSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook SlidesCSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook Slides
DanWooster1
 
Chapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loopsChapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loops
DanWooster1
 
Upstate CSCI 450 jQuery
Upstate CSCI 450 jQueryUpstate CSCI 450 jQuery
Upstate CSCI 450 jQuery
DanWooster1
 
Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13
DanWooster1
 
Ad

Recently uploaded (20)

All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Tax evasion, Tax planning & Tax avoidance.pptx
Tax evasion, Tax  planning &  Tax avoidance.pptxTax evasion, Tax  planning &  Tax avoidance.pptx
Tax evasion, Tax planning & Tax avoidance.pptx
manishbaidya2017
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
TechSoup
 
How to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo SlidesHow to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo Slides
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Lecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptxLecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptx
Arshad Shaikh
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdfRanking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Rafael Villas B
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Tax evasion, Tax planning & Tax avoidance.pptx
Tax evasion, Tax  planning &  Tax avoidance.pptxTax evasion, Tax  planning &  Tax avoidance.pptx
Tax evasion, Tax planning & Tax avoidance.pptx
manishbaidya2017
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
TechSoup
 
How to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo SlidesHow to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo Slides
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Lecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptxLecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptx
Arshad Shaikh
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdfRanking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Rafael Villas B
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 

Java Chapter 04 - Writing Classes: part 2

  • 1. Chapter 4 Writing Classes – Part 2 Java Software Solutions Foundations of Program Design 9th Edition John Lewis William Loftus
  • 2. Outline Anatomy of a Class Encapsulation Anatomy of a Method
  • 3. Key Concept • The heart of object-oriented programming is defining classes that represent objects with well-defined state and behavior.
  • 4. Writing Classes The programs we’ve written in previous examples have used classes defined in the Java API Now we will begin to design programs that rely on classes that we write ourselves The class that contains the main method is just the starting point of a program True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality
  • 6. Classes and Objects Recall from our overview of objects in Chapter 1 that an object has state and behavior Consider a six-sided die (singular of dice) Its state can be defined as which face is showing Its primary behavior is that it can be rolled We represent a die by designing a class called Die that models this state and behavior The class serves as the blueprint for a die object We can then instantiate as many die objects as we need for any particular program
  • 7. Classes • A class can contain data declarations and method declarations int size, weight; char category; Data declarations Method declarations
  • 8. Classes The values of the data define the state of an object created from the class The functionality of the methods define the behaviors of the object For our Die class, we might declare an integer called faceValue that represents the current value showing on the face One of the methods would “roll” the die by setting faceValue to a random number between one and six
  • 9. Classes We’ll want to design the Die class so that it is a versatile and reusable resource Any given program will probably not use all operations of a given class See RollingDice.java See Die.java
  • 10. //******************************************************************** // RollingDice.java Author: Lewis/Loftus // // Demonstrates the creation and use of a user-defined class. //******************************************************************** public class RollingDice { //----------------------------------------------------------------- // Creates two Die objects and rolls them several times. //----------------------------------------------------------------- public static void main(String[] args) { Die die1, die2; int sum; die1 = new Die(); die2 = new Die(); die1.roll(); die2.roll(); System.out.println("Die One: " + die1 + ", Die Two: " + die2); continue
  • 11. continue die1.roll(); die2.setFaceValue(4); System.out.println("Die One: " + die1 + ", Die Two: " + die2); sum = die1.getFaceValue() + die2.getFaceValue(); System.out.println("Sum: " + sum); sum = die1.roll() + die2.roll(); System.out.println("Die One: " + die1 + ", Die Two: " + die2); System.out.println("New sum: " + sum); } }
  • 12. continue die1.roll(); die2.setFaceValue(4); System.out.println("Die One: " + die1 + ", Die Two: " + die2); sum = die1.getFaceValue() + die2.getFaceValue(); System.out.println("Sum: " + sum); sum = die1.roll() + die2.roll(); System.out.println("Die One: " + die1 + ", Die Two: " + die2); System.out.println("New sum: " + sum); } } Sample Run Die One: 5, Die Two: 2 Die One: 1, Die Two: 4 Sum: 5 Die One: 4, Die Two: 2 New sum: 6
  • 13. //******************************************************************** // Die.java Author: Lewis/Loftus // // Represents one die (singular of dice) with faces showing values // between 1 and 6. //******************************************************************** public class Die { private final int MAX = 6; // maximum face value private int faceValue; // current value showing on the die //----------------------------------------------------------------- // Constructor: Sets the initial face value. //----------------------------------------------------------------- public Die() { faceValue = 1; } continue
  • 14. continue //----------------------------------------------------------------- // Rolls the die and returns the result. //----------------------------------------------------------------- public int roll() { faceValue = (int)(Math.random() * MAX) + 1; return faceValue; } //----------------------------------------------------------------- // Face value mutator. //----------------------------------------------------------------- public void setFaceValue(int value) { faceValue = value; } //----------------------------------------------------------------- // Face value accessor. //----------------------------------------------------------------- public int getFaceValue() { return faceValue; } continue
  • 15. continue //----------------------------------------------------------------- // Returns a string representation of this die. //----------------------------------------------------------------- public String toString() { String result = Integer.toString(faceValue); return result; } }
  • 16. The Die Class The Die class contains two data values a constant MAX that represents the maximum face value an integer faceValue that represents the current face value The roll method uses the random method of the Math class to determine a new face value There are also methods to explicitly set and retrieve the current face value at any time
  • 17. The toString Method It's good practice to define a toString method for a class The toString method returns a character string that represents the object in some way It is called automatically when an object is concatenated to a string or when it is passed to the println method It's also convenient for debugging problems
  • 18. Constructors As mentioned previously, a constructor is used to set up an object when it is initially created A constructor has the same name as the class The Die constructor is used to set the initial face value of each new die object to one We examine constructors in more detail later in this chapter
  • 19. Key Concept • The scope of a variable, which determines where it can be referenced, depends on where it is declared.
  • 20. Data Scope The scope of data is the area in a program in which that data can be referenced (used) Data declared at the class level can be referenced by all methods in that class Data declared within a method can be used only in that method Data declared within a method is called local data In the Die class, the variable result is declared inside the toString method -- it is local to that method and cannot be referenced anywhere else
  • 21. Instance Data A variable declared at the class level (such as faceValue) is called instance data Each instance (object) has its own instance variable A class declares the type of the data, but it does not reserve memory space for it Each time a Die object is created, a new faceValue variable is created as well The objects of a class share the method definitions, but each object has its own data space That's the only way two objects can have different states
  • 22. Instance Data • We can depict the two Die objects from the RollingDice program as follows: die1 5faceValue die2 2faceValue Each object maintains its own faceValue variable, and thus its own state
  • 23. Key Concept • A UML class diagram helps us visualize the contents of and relationships among the classes of a program.
  • 24. UML Diagrams UML stands for the Unified Modeling Language UML diagrams show relationships among classes and objects A UML class diagram consists of one or more classes, each with sections for the class name, attributes (data), and operations (methods) Lines between classes represent associations A dotted arrow shows that one class uses the other (calls its methods)
  • 25. UML Class Diagrams • A UML class diagram for the RollingDice program: RollingDice main (args : String[]) : void Die faceValue : int roll() : int setFaceValue (int value) : void getFaceValue() : int toString() : String