Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of...

62
Chapter 3 – Chapter 3 – Implementing Implementing Classes Classes

Transcript of Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of...

Page 1: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Chapter 3 – Chapter 3 – Implementing ClassesImplementing Classes

Page 2: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Chapter GoalsChapter Goals

To become familiar with the process of To become familiar with the process of implementing classes implementing classes To be able to implement simple methods To be able to implement simple methods To understand the purpose and use of To understand the purpose and use of constructors constructors To understand how to access instance To understand how to access instance fields and local variables fields and local variables To appreciate the importance of To appreciate the importance of documentation comments documentation comments

Page 3: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Black BoxBlack Box

A black box is A black box is something that something that performs a task, but performs a task, but hides how it does ithides how it does it

This is also called This is also called encapsulationencapsulation

Black boxes in a car: Black boxes in a car: transmission, electronic transmission, electronic control module, etc control module, etc

Page 4: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Levels of Levels of abstraction: abstraction:

Software Software DesignDesign

Page 5: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Old times: computer programs only Old times: computer programs only manipulated primitive types such as manipulated primitive types such as numbers and characters numbers and characters

Gradually programs became more Gradually programs became more complex, vastly increasing the amount of complex, vastly increasing the amount of detail a programmer had to remember and detail a programmer had to remember and maintainmaintain

Page 6: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

3.2 Designing the Public Interface 3.2 Designing the Public Interface to a Classto a Class

Your task: Develop a Your task: Develop a BankAccountBankAccount class class

First step: Define essential featuresFirst step: Define essential features

Behavior of bank account (abstraction):Behavior of bank account (abstraction): deposit money deposit money withdraw money withdraw money get balance get balance

Page 7: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Designing #1: MethodsDesigning #1: MethodsMethods of BankAccount class:Methods of BankAccount class: deposit deposit withdraw withdraw getBalance getBalance

Support method calls such as the following:Support method calls such as the following:harrysChecking.deposit(2000);harrysChecking.deposit(2000);

harrysChecking.withdraw(500);harrysChecking.withdraw(500);

System.out.println(harrysChecking.getBalance());System.out.println(harrysChecking.getBalance());

Which methods are accessors? Mutators?Which methods are accessors? Mutators?

Page 8: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Designing: Method DefinitionsDesigning: Method DefinitionsCOMPONENTS:COMPONENTS:

access specifieraccess specifier (Ex. public) (Ex. public)

return typereturn type (Ex. String or void) (Ex. String or void)

method name (Ex. deposit) method name (Ex. deposit)

list of list of parametersparameters (Ex. amount for deposit) (Ex. amount for deposit)

method method bodybody in braces {…} in braces {…}

Page 9: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Examples: Examples:

public void deposit(double amount) {...} public void deposit(double amount) {...}

public void withdraw(double amount) {...} public void withdraw(double amount) {...}

public double getBalance() {...} public double getBalance() {...}

Page 10: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Syntax 3.1: Method DefinitionSyntax 3.1: Method Definition

accessSpecifier returnType accessSpecifier returnType methodNamemethodName((parameterType parameterNameparameterType parameterName,...),...)

{{method bodymethod body

} }

Example:Example:    public void deposit(double amount){public void deposit(double amount){

. . .. . .}}

Purpose:Purpose:To define the behavior of a method To define the behavior of a method

Page 11: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Designing #2: ConstructorDesigning #2: Constructor

A constructor initializes the instance A constructor initializes the instance variables variables

Constructor name = class nameConstructor name = class name

public BankAccount()public BankAccount(){{

// body--filled in later// body--filled in later

} }

Page 12: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

ConstructorsConstructorsConstructor body is executed when new Constructor body is executed when new object is created object is created

Statements in constructor body will set the Statements in constructor body will set the internal data of the object that is being internal data of the object that is being constructedconstructed

How does the compile know which How does the compile know which constructor to call?constructor to call?

Page 13: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Constructor vs. MethodConstructor vs. Method

Constructors are a specialization of Constructors are a specialization of methodsmethods Goal: to set the internal data of the objectGoal: to set the internal data of the object

2 differences2 differences All constructors are named after the classAll constructors are named after the class

Therefore all constructors of a class have the Therefore all constructors of a class have the same namesame name

No return type listed EVER!No return type listed EVER!

Page 14: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Syntax 3.2 : Constructor Syntax 3.2 : Constructor DefinitionDefinition

accessSpecifier ClassNameaccessSpecifier ClassName((parameterType parameterType parameterNameparameterName, . . .), . . .){{

constructor bodyconstructor body }}

Example:Example:public BankAccount(double initialBalance)public BankAccount(double initialBalance)

{ { . . . . . .

}}

Purpose:Purpose:

To define the behavior of a constructor To define the behavior of a constructor

Page 15: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

BankAccountBankAccount Public Interface Public InterfaceThe public constructors and methods of a The public constructors and methods of a class form the class form the public interfacepublic interface of the class. of the class.

public class BankAccountpublic class BankAccount{{// private fields--filled in later // private fields--filled in later

// Constructors// Constructorspublic BankAccount()public BankAccount(){{

// body--filled in later // body--filled in later }}

Page 16: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

public BankAccount(double initialBalance) { public BankAccount(double initialBalance) { // body--filled in later// body--filled in later

} } // Methods // Methods public void deposit(double amount) {public void deposit(double amount) {

// body--filled in later// body--filled in later}}

public void withdraw(double amount) { public void withdraw(double amount) { // body--filled in later// body--filled in later

} }

public double getBalance() { public double getBalance() { // body--filled in // body--filled in later later

}}

} }

Page 17: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

RememberRemember

Public methods and constructors provide Public methods and constructors provide the the public interfacepublic interface to a class to a class They are how you interact with the black boxThey are how you interact with the black box

Our class is simple, but we can do many Our class is simple, but we can do many things with itthings with it Notice we haven’t defined the method body Notice we haven’t defined the method body

yet, but know how we can use ityet, but know how we can use it

Page 18: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

3.3 Commenting the Public 3.3 Commenting the Public InterfaceInterface

Part of creating a well-defined public Part of creating a well-defined public interface is always interface is always commentingcommenting the class the class and methods behaviorsand methods behaviors

The HTML pages from the API are created The HTML pages from the API are created from special comments in your program from special comments in your program called called javadoc commentsjavadoc comments

Place before the class or methodPlace before the class or method /**…/**…

....*/*/

Page 19: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Javadoc CommentsJavadoc CommentsBegin with Begin with /**/**

Ends withEnds with */*/

Put * on lines in between as Put * on lines in between as conventionconvention, , makes it easier to readmakes it easier to read

Javadoc tagsJavadoc tags - @ mark is one - @ mark is one @author, @param, @return@author, @param, @return

BenefitsBenefits Online documentation (Assignment 1)Online documentation (Assignment 1) Other java documentsOther java documents

Page 20: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Javadoc commentsJavadoc comments

First sentence is extracted for HTML pageFirst sentence is extracted for HTML page Carefully explain methodCarefully explain method

@param for each parameter@param for each parameter Omit if no parametersOmit if no parameters

@return for the value returned@return for the value returned Omit if return type voidOmit if return type void

Page 21: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

/**/** * Withdraws money from the bank account.* Withdraws money from the bank account. * @param the amount to withdraw* @param the amount to withdraw */*/

public void withdraw(double amount){public void withdraw(double amount){// implementation filled in later // implementation filled in later

}  }  

/**/** * Gets the current balance of the bank* Gets the current balance of the bank * account.* account. * @return the current balance* @return the current balance */*/public double getBalance(){public double getBalance(){// implementation filled in later// implementation filled in later

}}

Page 22: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Class CommentClass Comment

/**/**A bank account has a balance that canA bank account has a balance that canbe changed by deposits and withdrawals.be changed by deposits and withdrawals.

*/*/public class BankAccount{public class BankAccount{. . .. . .

} }

Page 23: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

3.4 Instance Fields3.4 Instance FieldsRemember: methods are the public Remember: methods are the public interface of a classinterface of a class

Instance Fields are part of the internal Instance Fields are part of the internal workings - An object stores its data in workings - An object stores its data in instance fieldsinstance fields FieldField: a technical term for a storage location : a technical term for a storage location

inside a block of memory inside a block of memory Instance of a classInstance of a class: an object of the class : an object of the class AKA Data MembersAKA Data Members

Page 24: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

The class declaration specifies the The class declaration specifies the instance fields:instance fields:public class BankAccountpublic class BankAccount{  {     private double balance;   private double balance;

......

} }

Page 25: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

An instance field declaration consists of An instance field declaration consists of the following parts: the following parts: access specifier (usually private) access specifier (usually private) type of variable (such as double) type of variable (such as double) name of variable (such as balance) name of variable (such as balance)

Each object of a class has its own set of Each object of a class has its own set of instance fields instance fields

You should declare all instance fields as You should declare all instance fields as private private

Page 26: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Access SpecifiersAccess SpecifiersAccess SpecifiersAccess Specifiers – defines the – defines the accessibility of the instance field and accessibility of the instance field and methodsmethods privateprivate – only accessible within the class – only accessible within the class

methodsmethods public public – accessible in outside class methods – accessible in outside class methods

and inside class methodsand inside class methods

Private enforces encapsulation/black boxPrivate enforces encapsulation/black box

AKA Visibility ModifierAKA Visibility Modifier

Page 27: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

  Syntax 3.4 : Instance Field Syntax 3.4 : Instance Field DeclarationDeclaration

accessSpecifieraccessSpecifier class class ClassNameClassName { . . .{ . . .accessSpecifier fieldType fieldNameaccessSpecifier fieldType fieldName;;. . . . . .

} }

Example:Example:public class BankAccountpublic class BankAccount{{

. . .. . .private double balance;private double balance;. . .. . .

} }

Purpose: Purpose: To define a field that is present in every object To define a field that is present in every object of a class of a class

Page 28: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Accessing Instance FieldsAccessing Instance Fields

The deposit method of the BankAccount The deposit method of the BankAccount class can access the private instance field:class can access the private instance field:

public void deposit(double amount)public void deposit(double amount){{   double newBalance = balance + amount;   double newBalance = balance + amount;   balance = newBalance;   balance = newBalance;} }

Page 29: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Other methods cannot:Other methods cannot:

public class BankRobberpublic class BankRobber{{   public static void main(String[] args)   public static void main(String[] args)   {   {     BankAccount momsSavings = new      BankAccount momsSavings = new

BankAccount(1000);BankAccount(1000);     . . .     . . .     momsSavings.balance = -1000; // ERROR     momsSavings.balance = -1000; // ERROR   }   }} }

Page 30: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Encapsulation = Hiding data and providing Encapsulation = Hiding data and providing access through methods access through methods

By making data members private, we hide By making data members private, we hide internal workings of a class from a userinternal workings of a class from a user

Note: We can have public instance fields Note: We can have public instance fields and private methods, but commonly we do and private methods, but commonly we do notnot

Page 31: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

3.5 Implementing Constructors & 3.5 Implementing Constructors & MethodsMethods

Constructors contain instructions to Constructors contain instructions to initialize the instance fields of an object initialize the instance fields of an object public BankAccount()public BankAccount(){{

balance = 0;balance = 0;}}

public BankAccount(double initialBalance)public BankAccount(double initialBalance){{

balance = initialBalance;balance = initialBalance;} }

Page 32: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Constructor Call ExampleConstructor Call ExampleBankAccount harrysChecking = new BankAccount harrysChecking = new BankAccount(1000); BankAccount(1000); Create a new object of type BankAccount Create a new object of type BankAccount Call the second constructor (since a construction Call the second constructor (since a construction

parameter is supplied) parameter is supplied) Set the parameter variable initialBalance to 1000 Set the parameter variable initialBalance to 1000 Set the balance instance field of the newly created Set the balance instance field of the newly created

object to initialBalance object to initialBalance Return an object reference, that is, the memory Return an object reference, that is, the memory

location of the object, as the value of the new location of the object, as the value of the new expression expression

Store that object reference in the harrysChecking Store that object reference in the harrysChecking variable variable

Page 33: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Why put instructions in a method?Why put instructions in a method?

… … or why not just have one long list of or why not just have one long list of instructions in our programs?instructions in our programs?

1.1. smaller smaller easier easier

2.2. test & debug once, execute as often as test & debug once, execute as often as neededneeded

3.3. more readable codemore readable code

Page 34: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Implementing MethodsImplementing Methods

Some methods do not return a value Some methods do not return a value public void withdraw(double amount)public void withdraw(double amount){{

double newBalance = balance - amount;double newBalance = balance - amount;balance = newBalance;balance = newBalance;

} }

Some methods return an output value Some methods return an output value public double getBalance()public double getBalance(){{

return balance;return balance;}}

Page 35: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Method Call ExampleMethod Call Example

harrysChecking.deposit(500); harrysChecking.deposit(500); Set the parameter variable amount to 500 Set the parameter variable amount to 500 Fetch the Fetch the balancebalance field of the object whose field of the object whose

location is stored in location is stored in harrysChecking harrysChecking Add the value of amount to Add the value of amount to balancebalance and store and store

the result in the variable the result in the variable newBalancenewBalance Store the value of Store the value of newBalancenewBalance in the in the balancebalance

instance field, overwriting the old value instance field, overwriting the old value

Page 36: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Syntax 3.5: The return StatementSyntax 3.5: The return Statement

return return expressionexpression;; or  or

return;return;

Example:Example:return balance;return balance;

Purpose:Purpose:To specify the value that a method returns, To specify the value that a method returns, and exit the method immediately. The and exit the method immediately. The return value becomes the value of the return value becomes the value of the method call expression. method call expression.

Page 37: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
Page 38: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
Page 39: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
Page 40: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Wu’s TemplateWu’s Template

Page 41: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

/** Stores information about one pet. *//** Stores information about one pet. */public class Pet {public class Pet {

/** Name of the pet. *//** Name of the pet. */private String name, kind;private String name, kind;private int age;private int age;

/** Initializes a new instance./** Initializes a new instance. * @param n The pet's name.* @param n The pet's name. */*/ public Pet( String n, String k, int a ) {public Pet( String n, String k, int a ) {

name = n; kind = k; age = a;name = n; kind = k; age = a; }}

/** Returns the name of this pet. *//** Returns the name of this pet. */ public String getName() { return name; }public String getName() { return name; }

/** Changes the name of this pet./** Changes the name of this pet. * @param newName The new name of the pet.* @param newName The new name of the pet. */*/ public void changeNameTo( String newName ) {public void changeNameTo( String newName ) { // TEST THE NAME HERE// TEST THE NAME HERE name = newName;name = newName; }}}}

Data member

Constructor

Methods

Page 42: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

3.6 Testing Classes3.6 Testing ClassesPrevious section was designing a classPrevious section was designing a class

By itself, we cannot actually run a programBy itself, we cannot actually run a program No main() method, like most classesNo main() method, like most classes

We create instances of it in other classesWe create instances of it in other classes

Idea: use a test class to make sure it Idea: use a test class to make sure it works properly before dispensing the works properly before dispensing the productproduct

Page 43: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

3.6 Testing A Class3.6 Testing A ClassTest class: a class with a main method Test class: a class with a main method that contains statements to test another that contains statements to test another class. class.

Typically carries out the following steps: Typically carries out the following steps: Construct one or more objects of the class Construct one or more objects of the class

that is being tested that is being tested Invoke one or more methods Invoke one or more methods Print out one or more results Print out one or more results Verify output is correct and program behaves Verify output is correct and program behaves

as expectedas expected

Page 44: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

/** A Test Program. *//** A Test Program. */public class TestPet {public class TestPet {

/** /** * Test Program starts here. * Test Program starts here. * @param args Unused in this program.* @param args Unused in this program. */*/ public static void main( String [] args ) {public static void main( String [] args ) {

// Declare and create a pet// Declare and create a pet Pet pet1 = new Pet( "George", "bird", 14 );Pet pet1 = new Pet( "George", "bird", 14 );

// Test the pet's information// Test the pet's information System.out.println( pet1.getName() +System.out.println( pet1.getName() +

“ “ (should be George)” );(should be George)” );}}

}}

Page 45: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

/** /**

* A class to test the BankAccount class. * A class to test the BankAccount class.

*/ */

public class BankAccountTester{ public class BankAccountTester{

/** /**

*Tests the methods of the BankAccount class. *Tests the methods of the BankAccount class.

*@param args not used *@param args not used

*/ */

public static void main(String[] args){ public static void main(String[] args){

BankAccount harrysChecking = new BankAccount();BankAccount harrysChecking = new BankAccount();

harrysChecking.deposit(2000); harrysChecking.deposit(2000);

harrysChecking.withdraw(500); harrysChecking.withdraw(500);

System.out.println(harrysChecking.getBalance()); System.out.println(harrysChecking.getBalance());

} }

} }

Page 46: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

3.7 Categories of Variables3.7 Categories of Variables

Categories of variables Categories of variables Instance fields (balance in BankAccount) Instance fields (balance in BankAccount) Local variables (newBalance in deposit method) Local variables (newBalance in deposit method) Parameter variables (amount in deposit method) Parameter variables (amount in deposit method)

Share the same properties of declaring and Share the same properties of declaring and creatingcreating

Differ in their Differ in their lifetime (lifetime (AKAAKA scope) scope)

Page 47: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Instance FieldInstance Field

An instance field belongs to an object An instance field belongs to an object AKA Instance variableAKA Instance variable Each object has its own copy of the instance Each object has its own copy of the instance

fieldfield

The fields stay alive until no method uses The fields stay alive until no method uses the object any longer the object any longer

More specifically, until the object no longer More specifically, until the object no longer existsexists

Page 48: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Local VariablesLocal Variables

Local and parameter variables belong to a Local and parameter variables belong to a methodmethod You declare them and create within the methodYou declare them and create within the method

When method is done executing, variable is When method is done executing, variable is thrown out thrown out Every time the method is executed, a new copy Every time the method is executed, a new copy

of any variables is created, values do not carry of any variables is created, values do not carry overover

Page 49: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Lifetime Of VariablesLifetime Of Variables

Say we made the following method callSay we made the following method call

harrysChecking.deposit(500);harrysChecking.deposit(500);

Remember thatRemember that deposit deposit looks like thislooks like this

public void deposit(double amount) {public void deposit(double amount) {

double newBalance = balance + amount;double newBalance = balance + amount;

balance = newBalance; balance = newBalance;

}}

Page 50: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
Page 51: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

3.8 Implicit and Explicit Method 3.8 Implicit and Explicit Method ParametersParameters

The implicit parameter of a method is the The implicit parameter of a method is the object on which the method is invoked object on which the method is invoked

Why is this important?Why is this important?

When a method is invoked, and an When a method is invoked, and an instance field is used, how does it know instance field is used, how does it know which object it belongs to?which object it belongs to?

Page 52: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Use of an instance field name in a method Use of an instance field name in a method denotes the instance field of the implicit denotes the instance field of the implicit parameter – the object it is called onparameter – the object it is called on

public void withdraw(double amount)public void withdraw(double amount){{

double newBalance = double newBalance = balancebalance - - amount;amount;

balancebalance = newBalance; = newBalance;}}

Page 53: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

balancebalance is the is the balancebalance of the object to the of the object to the left of the dot:left of the dot:

momsSavings.withdraw(500);momsSavings.withdraw(500);

means means

double newBalance = double newBalance = momsSavings.balancemomsSavings.balance - - amount;amount;momsSavings.balancemomsSavings.balance = newBalance; = newBalance;

Page 54: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Implicit Parameters and Implicit Parameters and thisthisEvery method has one implicit parameter Every method has one implicit parameter

The method knows what object called it based The method knows what object called it based on a reference, but does not know/care about on a reference, but does not know/care about the identifier namethe identifier name E.g. you cannot say momsSavings.balance in the E.g. you cannot say momsSavings.balance in the

class, because momsSavings is a local variable of class, because momsSavings is a local variable of another classanother class

So in order to be more general, we call the So in order to be more general, we call the implicit parameter implicit parameter thisthis

Exception: Static methods do not have an Exception: Static methods do not have an implicit parameter (more on Chapter 9) implicit parameter (more on Chapter 9)

Page 55: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Implicit Parameters and Implicit Parameters and thisthis

double newBalance = balance + amount;double newBalance = balance + amount;// actually means// actually meansdouble newBalance = this.balance + amount; double newBalance = this.balance + amount;

When you refer to an instance field in a When you refer to an instance field in a method, the compiler automatically applies method, the compiler automatically applies it to the it to the thisthis parameter parameter

Page 56: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Example – without thisExample – without thispublic class BankAccount{public class BankAccount{double balance;double balance;

public BankAccount(double initialBalance){public BankAccount(double initialBalance){balance = initialBalance;balance = initialBalance;

}}

public BankAccount(){public BankAccount(){balance = 0;balance = 0;

}}……}}

Page 57: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Example – with thisExample – with this

public class BankAccount{public class BankAccount{double balance;double balance;

public BankAccount(double initialBalance){public BankAccount(double initialBalance){balance = initialBalance;balance = initialBalance;

}}

public BankAccount(){public BankAccount(){this(0);this(0);

}}……}}

Page 58: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

HOW TO 3.1 – Designing and HOW TO 3.1 – Designing and Implementing a ClassImplementing a Class

Step 1: Find out what you are asked to do Step 1: Find out what you are asked to do with an object of the classwith an object of the class What do you want to be able to do with the What do you want to be able to do with the

object?object?

Step 2: Specify the Public InterfaceStep 2: Specify the Public Interface Convert the list from step 1 into methods, and Convert the list from step 1 into methods, and

the parameters (think: input) they needthe parameters (think: input) they need Constructors: how do I want to initialize this Constructors: how do I want to initialize this

objectobject

Page 59: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

HOW-TO 3.1 (cont)HOW-TO 3.1 (cont)

Step 3: Document the public interfaceStep 3: Document the public interface Create Javadoc comments for each method Create Javadoc comments for each method

and the classand the class

Step 4: Determine instance fieldsStep 4: Determine instance fields What information needs to be maintained?What information needs to be maintained?

Step 5: ImplementStep 5: Implement One at a time, from easiest to most difficultOne at a time, from easiest to most difficult

Page 60: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

HOW-TO 3.1 (cont)HOW-TO 3.1 (cont)

Go back to Step 2 if implementation Go back to Step 2 if implementation doesn’t workdoesn’t work

Step 6: Test your classStep 6: Test your class

Page 61: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Note on Style #1Note on Style #1 A couple ways to use curly bracesA couple ways to use curly braces

Option #1Option #1public class SomeClass{public class SomeClass{……}}

Option #2Option #2public class SomeClasspublic class SomeClass{{……}}

Page 62: Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.

Note on Style #2Note on Style #2Book says to place instance fields at the Book says to place instance fields at the bottom of a classbottom of a class

public class SomeClass{public class SomeClass{

//constructors//constructors

//methods//methods

//instance fields//instance fields

}}

Most conventions have it at the top of a classMost conventions have it at the top of a classpublic class SomeClass{public class SomeClass{

//instance fields//instance fields

//constructors//constructors

//methods//methods

}}