SlideShare una empresa de Scribd logo
1 de 25
Chapter 4
Writing Classes
– Part 4
Java Software Solutions
Foundations of Program Design
9th Edition
John Lewis
William Loftus
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Method
Declarations
Let’s now examine
methods in more detail
A method declaration
specifies the code that will
be executed when the
method is invoked (called)
When a method is invoked,
the flow of control jumps
to the method and
executes its code
When complete, the flow
returns to the place where
the method was called and
continues
The invocation may or may
not return a value,
depending on how the
method is defined
myMethod();
myMethodcompute
Method Control Flow
• If the called method is in the same class, only the
method name is needed
doIt helpMe
helpMe();obj.doIt();
main
Method Control Flow
• The called method is often part of another class or
object
Method Header
• A method declaration begins with a method header
char calc(int num1, int num2, String message)
method
name
return
type
parameter list
The parameter list specifies the type
and name of each parameter
The name of a parameter in the method
declaration is called a formal parameter
Method Body
• The method header is followed by the method body
char calc(int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt(sum);
return result;
}
The return expression
must be consistent with
the return type
sum and result
are local data
They are created
each time the
method is called, and
are destroyed when
it finishes executing
Key Concept
The value returned from a
method must be consistent
with the return type in the
method header.
The return
Statement
The return type of a method indicates the type of value
that the method sends back to the calling location
A method that does not return a value has a void return
type
A return statement specifies the value that will be
returned
return expression;
Its expression must conform to the return type
Key Concept
When a method is called, the
actual parameters are copied
into the formal parameters.
Parameters
• When a method is called, the actual parameters in the
invocation are copied into the formal parameters in the
method header
char calc(int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt(sum);
return result;
}
ch = obj.calc(25, count, "Hello");
Key Concept
A variable declared in a
method is local to that method
and cannot be used outside of
it.
Local Data
As we’ve seen, local variables can be
declared inside a method
The formal parameters of a method create
automatic local variables when the
method is invoked
When the method finishes, all local
variables are destroyed (including the
formal parameters)
Keep in mind that instance variables,
declared at the class level, exists as long
as the object exists
Bank Account
Example
Let’s look at
another example
that demonstrates
the
implementation
details of classes
and methods
We’ll represent a
bank account by a
class named
Account
It’s state can
include the account
number, the
current balance,
and the name of
the owner
An account’s
behaviors (or
services) include
deposits and
withdrawals, and
adding interest
Driver
Programs
A driver program drives the use of other, more interesting
parts of a program
Driver programs are often used to test other parts of the
software
The Transactions class contains a main method that drives
the use of the Account class, exercising its services
See Transactions.java
See Account.java
//********************************************************************
// Transactions.java Author: Lewis/Loftus
//
// Demonstrates the creation and use of multiple Account objects.
//********************************************************************
public class Transactions
{
//-----------------------------------------------------------------
// Creates some bank accounts and requests various services.
//-----------------------------------------------------------------
public static void main(String[] args)
{
Account acct1 = new Account("Ted Murphy", 72354, 102.56);
Account acct2 = new Account("Jane Smith", 69713, 40.00);
Account acct3 = new Account("Edward Demsey", 93757, 759.32);
acct1.deposit(25.85);
double smithBalance = acct2.deposit(500.00);
System.out.println("Smith balance after deposit: " +
smithBalance);
continue
continue
System.out.println("Smith balance after withdrawal: " +
acct2.withdraw (430.75, 1.50));
acct1.addInterest();
acct2.addInterest();
acct3.addInterest();
System.out.println();
System.out.println(acct1);
System.out.println(acct2);
System.out.println(acct3);
}
}
continue
System.out.println("Smith balance after withdrawal: " +
acct2.withdraw (430.75, 1.50));
acct1.addInterest();
acct2.addInterest();
acct3.addInterest();
System.out.println();
System.out.println(acct1);
System.out.println(acct2);
System.out.println(acct3);
}
}
Output
Smith balance after deposit: 540.0
Smith balance after withdrawal: 107.55
72354 Ted Murphy $132.90
69713 Jane Smith $111.52
93757 Edward Demsey $785.90
//********************************************************************
// Account.java Author: Lewis/Loftus
//
// Represents a bank account with basic services such as deposit
// and withdraw.
//********************************************************************
import java.text.NumberFormat;
public class Account
{
private final double RATE = 0.035; // interest rate of 3.5%
private long acctNumber;
private double balance;
private String name;
//-----------------------------------------------------------------
// Sets up the account by defining its owner, account number,
// and initial balance.
//-----------------------------------------------------------------
public Account(String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
continue
continue
//-----------------------------------------------------------------
// Deposits the specified amount into the account. Returns the
// new balance.
//-----------------------------------------------------------------
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
//-----------------------------------------------------------------
// Withdraws the specified amount from the account and applies
// the fee. Returns the new balance.
//-----------------------------------------------------------------
public double withdraw(double amount, double fee)
{
balance = balance - amount - fee;
return balance;
}
continue
continue
//-----------------------------------------------------------------
// Adds interest to the account and returns the new balance.
//-----------------------------------------------------------------
public double addInterest()
{
balance += (balance * RATE);
return balance;
}
//-----------------------------------------------------------------
// Returns the current balance of the account.
//-----------------------------------------------------------------
public double getBalance()
{
return balance;
}
//-----------------------------------------------------------------
// Returns a one-line description of the account as a string.
//-----------------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return (acctNumber + "t" + name + "t" + fmt.format(balance));
}
}
Bank Account Example
acct1 72354acctNumber
102.56balance
name "Ted Murphy"
acct2 69713acctNumber
40.00balance
name "Jane Smith"
Bank Account
Example
There are some improvements that can be
made to the Account class
Formal getters and setters could have been
defined for all data
The design of some methods could also be
more robust, such as verifying that the
amount parameter to the withdraw method
is positive
Key Concept
A constructor cannot have any
return type, even void.
Constructors
Revisited
Note that a constructor has no return type
specified in the method header, not even void
A common error is to put a return type on a
constructor, which makes it a “regular” method
that happens to have the same name as the class
The programmer does not have to define a
constructor for a class
Each class has a default constructor that accepts
no parameters

Más contenido relacionado

La actualidad más candente

java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
Variables in python
Variables in pythonVariables in python
Variables in pythonJaya Kumari
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual BasicSangeetha Sg
 
Abap Inicio
Abap InicioAbap Inicio
Abap Iniciounifor
 
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 KuteTushar B Kute
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Inheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismInheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismJawad Khan
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keywordtanu_jaswal
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoopSeo Gyansha
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfacesDevaKumari Vijay
 

La actualidad más candente (20)

Oops
OopsOops
Oops
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
C++ classes
C++ classesC++ classes
C++ classes
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Inheritance
InheritanceInheritance
Inheritance
 
Java interface
Java interfaceJava interface
Java interface
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
Abap Inicio
Abap InicioAbap Inicio
Abap Inicio
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
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
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Inheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismInheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphism
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Classes2
Classes2Classes2
Classes2
 
Inheritance
InheritanceInheritance
Inheritance
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Inheritance
InheritanceInheritance
Inheritance
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 

Similar a Java Chapter 04 - Writing Classes: part 4

EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...vekariyakashyap
 
Ive posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfIve posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfdeepaarora22
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101Thomas Lee
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaHamad Odhabi
 
C0 review core java1
C0 review core java1C0 review core java1
C0 review core java1tam53pm1
 

Similar a Java Chapter 04 - Writing Classes: part 4 (20)

Methods.ppt
Methods.pptMethods.ppt
Methods.ppt
 
Ifi7107 lesson4
Ifi7107 lesson4Ifi7107 lesson4
Ifi7107 lesson4
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Savitch ch 04
Savitch ch 04Savitch ch 04
Savitch ch 04
 
Class
ClassClass
Class
 
Ive posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfIve posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdf
 
Subprogramms
SubprogrammsSubprogramms
Subprogramms
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Class 10
Class 10Class 10
Class 10
 
Classes
ClassesClasses
Classes
 
Functions
FunctionsFunctions
Functions
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
Vb (1)
Vb (1)Vb (1)
Vb (1)
 
C0 review core java1
C0 review core java1C0 review core java1
C0 review core java1
 
Savitch Ch 04
Savitch Ch 04Savitch Ch 04
Savitch Ch 04
 

Más de DanWooster1

Upstate CSCI 540 Agile Development
Upstate CSCI 540 Agile DevelopmentUpstate CSCI 540 Agile Development
Upstate CSCI 540 Agile DevelopmentDanWooster1
 
Upstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testingUpstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testingDanWooster1
 
Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9DanWooster1
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4DanWooster1
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4DanWooster1
 
Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3DanWooster1
 
Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2DanWooster1
 
Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1DanWooster1
 
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 3DanWooster1
 
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 2DanWooster1
 
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 1DanWooster1
 
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 - ArraysDanWooster1
 
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 - OOPDanWooster1
 
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 ClassesDanWooster1
 
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 & ExpressionsDanWooster1
 
CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01DanWooster1
 
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 SlidesDanWooster1
 
Chapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loopsChapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loopsDanWooster1
 
Upstate CSCI 450 jQuery
Upstate CSCI 450 jQueryUpstate CSCI 450 jQuery
Upstate CSCI 450 jQueryDanWooster1
 
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, 13DanWooster1
 

Más de DanWooster1 (20)

Upstate CSCI 540 Agile Development
Upstate CSCI 540 Agile DevelopmentUpstate CSCI 540 Agile Development
Upstate CSCI 540 Agile Development
 
Upstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testingUpstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testing
 
Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4
 
Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3
 
Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2
 
Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01
 
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
 
Chapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loopsChapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loops
 
Upstate CSCI 450 jQuery
Upstate CSCI 450 jQueryUpstate CSCI 450 jQuery
Upstate CSCI 450 jQuery
 
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
 

Último

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 

Último (20)

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 

Java Chapter 04 - Writing Classes: part 4

  • 1. Chapter 4 Writing Classes – Part 4 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. Method Declarations Let’s now examine methods in more detail A method declaration specifies the code that will be executed when the method is invoked (called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined
  • 4. myMethod(); myMethodcompute Method Control Flow • If the called method is in the same class, only the method name is needed
  • 5. doIt helpMe helpMe();obj.doIt(); main Method Control Flow • The called method is often part of another class or object
  • 6. Method Header • A method declaration begins with a method header char calc(int num1, int num2, String message) method name return type parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter
  • 7. Method Body • The method header is followed by the method body char calc(int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt(sum); return result; } The return expression must be consistent with the return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing
  • 8. Key Concept The value returned from a method must be consistent with the return type in the method header.
  • 9. The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type A return statement specifies the value that will be returned return expression; Its expression must conform to the return type
  • 10. Key Concept When a method is called, the actual parameters are copied into the formal parameters.
  • 11. Parameters • When a method is called, the actual parameters in the invocation are copied into the formal parameters in the method header char calc(int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt(sum); return result; } ch = obj.calc(25, count, "Hello");
  • 12. Key Concept A variable declared in a method is local to that method and cannot be used outside of it.
  • 13. Local Data As we’ve seen, local variables can be declared inside a method The formal parameters of a method create automatic local variables when the method is invoked When the method finishes, all local variables are destroyed (including the formal parameters) Keep in mind that instance variables, declared at the class level, exists as long as the object exists
  • 14. Bank Account Example Let’s look at another example that demonstrates the implementation details of classes and methods We’ll represent a bank account by a class named Account It’s state can include the account number, the current balance, and the name of the owner An account’s behaviors (or services) include deposits and withdrawals, and adding interest
  • 15. Driver Programs A driver program drives the use of other, more interesting parts of a program Driver programs are often used to test other parts of the software The Transactions class contains a main method that drives the use of the Account class, exercising its services See Transactions.java See Account.java
  • 16. //******************************************************************** // Transactions.java Author: Lewis/Loftus // // Demonstrates the creation and use of multiple Account objects. //******************************************************************** public class Transactions { //----------------------------------------------------------------- // Creates some bank accounts and requests various services. //----------------------------------------------------------------- public static void main(String[] args) { Account acct1 = new Account("Ted Murphy", 72354, 102.56); Account acct2 = new Account("Jane Smith", 69713, 40.00); Account acct3 = new Account("Edward Demsey", 93757, 759.32); acct1.deposit(25.85); double smithBalance = acct2.deposit(500.00); System.out.println("Smith balance after deposit: " + smithBalance); continue
  • 17. continue System.out.println("Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50)); acct1.addInterest(); acct2.addInterest(); acct3.addInterest(); System.out.println(); System.out.println(acct1); System.out.println(acct2); System.out.println(acct3); } }
  • 18. continue System.out.println("Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50)); acct1.addInterest(); acct2.addInterest(); acct3.addInterest(); System.out.println(); System.out.println(acct1); System.out.println(acct2); System.out.println(acct3); } } Output Smith balance after deposit: 540.0 Smith balance after withdrawal: 107.55 72354 Ted Murphy $132.90 69713 Jane Smith $111.52 93757 Edward Demsey $785.90
  • 19. //******************************************************************** // Account.java Author: Lewis/Loftus // // Represents a bank account with basic services such as deposit // and withdraw. //******************************************************************** import java.text.NumberFormat; public class Account { private final double RATE = 0.035; // interest rate of 3.5% private long acctNumber; private double balance; private String name; //----------------------------------------------------------------- // Sets up the account by defining its owner, account number, // and initial balance. //----------------------------------------------------------------- public Account(String owner, long account, double initial) { name = owner; acctNumber = account; balance = initial; } continue
  • 20. continue //----------------------------------------------------------------- // Deposits the specified amount into the account. Returns the // new balance. //----------------------------------------------------------------- public double deposit(double amount) { balance = balance + amount; return balance; } //----------------------------------------------------------------- // Withdraws the specified amount from the account and applies // the fee. Returns the new balance. //----------------------------------------------------------------- public double withdraw(double amount, double fee) { balance = balance - amount - fee; return balance; } continue
  • 21. continue //----------------------------------------------------------------- // Adds interest to the account and returns the new balance. //----------------------------------------------------------------- public double addInterest() { balance += (balance * RATE); return balance; } //----------------------------------------------------------------- // Returns the current balance of the account. //----------------------------------------------------------------- public double getBalance() { return balance; } //----------------------------------------------------------------- // Returns a one-line description of the account as a string. //----------------------------------------------------------------- public String toString() { NumberFormat fmt = NumberFormat.getCurrencyInstance(); return (acctNumber + "t" + name + "t" + fmt.format(balance)); } }
  • 22. Bank Account Example acct1 72354acctNumber 102.56balance name "Ted Murphy" acct2 69713acctNumber 40.00balance name "Jane Smith"
  • 23. Bank Account Example There are some improvements that can be made to the Account class Formal getters and setters could have been defined for all data The design of some methods could also be more robust, such as verifying that the amount parameter to the withdraw method is positive
  • 24. Key Concept A constructor cannot have any return type, even void.
  • 25. Constructors Revisited Note that a constructor has no return type specified in the method header, not even void A common error is to put a return type on a constructor, which makes it a “regular” method that happens to have the same name as the class The programmer does not have to define a constructor for a class Each class has a default constructor that accepts no parameters