55
Chapter 3 Implementing Classes

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

  • View
    215

  • Download
    1

Embed Size (px)

Citation preview

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 understand

Chapter 3

Implementing 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 understand

Chapter Goals

• To become familiar with the process of implementing classes

• To be able to implement simple methods

• To understand the purpose and use of constructors

• To understand how to access instance fields and local variables

• To appreciate the importance of 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 understand

Black Boxes

• A black box magically does its thing

• Hides its inner workings

• Encapsulation: the hiding of unimportant details

• What is the right concept for each particular black box?

Continued…

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 understand

Black Boxes

• Concepts are discovered through abstraction

• Abstraction: taking away inessential features, until only the essence of the concept remains

• In object-oriented programming the black boxes from which a program is manufactured are called objects

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 understand

Levels of Abstraction: A Real-Life Example

Figure 1:Levels of Abstraction in Automobile Design

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

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 understand

Levels of Abstraction: A Real- Life Example• Users of a car do not need to understand how black

boxes work

• Interaction of a black box with outside world is well-defined Drivers interact with car using pedals, buttons, etc. Mechanic can test that engine control module sends the

right firing signals to the spark plugs For engine control module manufacturers, transistors

and capacitors are black boxes magically produced by an electronics component manufacturer

Continued…

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 understand

Levels of Abstraction: A Real- Life Example

• Encapsulation leads to efficiency: Mechanic deals only with car components

(e.g. electronic control module), not with sensors and transistors

Driver worries only about interaction with car (e.g. putting gas in the tank), not about motor or electronic control module

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 understand

Levels of Abstraction: Software Design

Figure 2:Levels of Abstraction in Software Design

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 understand

Levels of Abstraction: Software Design

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

• Manipulating too many of these primitive quantities is too much for programmers and leads to errors

• Solution: Encapsulate routine computations to software black boxes

Continued…

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 understand

Levels of Abstraction: Software Design

• Abstraction used to invent higher-level data types

• In object-oriented programming, objects are black boxes

• Encapsulation: Programmer using an object knows about its behavior, but not about its internal structure

Continued…

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 understand

Levels of Abstraction: Software Design

• In software design, you can design good and bad abstractions with equal facility; understanding what makes good design is an important part of the education of a software engineer

• First, define behavior of a class; then, implement it

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 understand

Designing the Public Interface of a Class

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

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 understand

Designing the Public Interface of a Class: Methods

• Methods of BankAccount class:

• We want to support method calls such as the following:

harrysChecking.deposit(2000);harrysChecking.withdraw(500);System.out.println(harrysChecking.getBalance());

deposit withdraw getBalance

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 understand

Designing the Public Interface of a Class: Method Definition

• access specifier (such as public)

• return type (such as String or void)

• method name (such as deposit)

• list of parameters (double amount for deposit)

• method body in { }

Continued…

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 understand

Designing the Public Interface of a Class: Method Definition

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

Examples

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 understand

Syntax 3.1: Method Definition

accessSpecifier returnType methodName(parameterType parameterName, . . .){ method body }

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

Purpose:To define the behavior of a method

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 understand

Designing the Public Interface of a Class: Constructor Definition

• A constructor initializes the instance variables

• Constructor name = class name

public BankAccount(){ // body--filled in later }

Continued…

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 understand

Designing the Public Interface of a Class: Constructor Definition

• Constructor body is executed when new object is created

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

• All constructors of a class have the same name

• Compiler can tell constructors apart because they take different parameters

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 understand

Syntax 3.2: Constructor Definition

accessSpecifier ClassName(parameterType parameterName, . . .) { constructor body }

Example:  public BankAccount(double initialBalance) { . . . }

Purpose:To define the behavior of a constructor

NOTE: Constructor are methods like any other, but they don’t have any listed return type: because they always return an Object of their class.

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 understand

BankAccount Public Interface• The public constructors and methods of a

class form the public interface of the class.

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

// Methods public void deposit(double amount) Continued…

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 understand

BankAccount Public Interface

{ // body--filled in later }

public void withdraw(double amount) { // body--filled in later } public double getBalance() { // body--filled in later } // private fields--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 understand

Syntax 3.3: Class Definition accessSpecifier class ClassName { constructors methods fields }

Example: public class BankAccount { public BankAccount(double initialBalance) { . . . } public void deposit(double amount) { . . . } . . . }

Purpose:To define a class, its public interface, and its implementation details

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 understand

Commenting on the Public Interface/** Withdraws money from the bank account. @param the amount to withdraw*/public void withdraw(double amount){ // implementation filled in later }

This is a Javadoc comment: a comment written in a particular form so that it can be processed by a program called javadoc, that automatically generates documentation for your programs.

The /** indicates the start of a Javadoc comment.

First sentence of the comment describes the method in question.

The @param line explains the input parameters to this method.

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 understand

Commenting on the Public Interface

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

• Again, a Javadoc comment: written in the particular form that can be processed by a javadoc, . Javadoc is a standard part of java, that generates, among other things, the API.

• The /** indicates the start of a Javadoc comment.

• First sentence of the comment describes the method in question.

• The @return line explains the return value given by this method.

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 understand

Class Comment

/** A bank account has a balance that can be changed by deposits and withdrawals.*/public class BankAccount{ . . .}

• This shows a javadoc comment for a class.• You should provide comments for

every class every method every parameter every return value.

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 understand

Javadoc Method Summary

Figure 3:A Method Summary Generated by javadoc from the definitions and comments given earlier. Javadoc comes with java and produces summaries as above.

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 understand

Javadoc Method Detail

Figure 4:Method Detail Generated by javadoc. To run javadoc for a particular class, use javadoc myClass.java. The output is placed in myClass.html

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 understand

Instance Fields

• An object stores its data in instance fields (instance variables).

• Field: a technical term for a storage location inside a block of memory

• Instance of a class: an object of the class

• The class declaration specifies instance fields:

public class BankAccount{     . . .   private double balance;}

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 understand

Instance Fields• An instance field declaration consists of the following parts:

access specifier (such as private) type of variable (such as double) name of variable (such as balance)

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

• The current style in java is to declare all instance fields as private (which means they cannot be seen from outside the object to which they belong).

• Private instance fields are accessed and changed via accessor (getter) and mutator (setter) methods, which can include code to ensure that only legitimate changes to field values can occur.

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 understand

Instance Fields

Figure 5:Instance Fields

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 understand

Syntax 3.4: Instance Field Declaration

 accessSpecifier class ClassName { . . . accessSpecifier fieldType fieldName; . . . }

Example: public class BankAccount { . . . private double balance; . . . }

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

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 understand

Accessing Instance Fields

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

Continued…

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

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 understand

Accessing Instance Fields• Methods in other classes cannot:

• Encapsulation = Hiding data and providing access through methods

public class BankRobber{   public static void main(String[] args)   {     BankAccount momsSavings = new BankAccount(1000);     . . .     momsSavings.balance = -1000; // ERROR   }}

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 understand

Implementing Constructors

• Constructors contain instructions to initialize the instance fields of an object

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

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 understand

Constructor Call Example

Create a new object of type BankAccount Call the second constructor (since a construction parameter

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

Return an object reference, that is, the memory location of the object, as the value of the new expression

Store that object reference in the harrysChecking variable

BankAccount harrysChecking = new BankAccount(1000);

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 understand

Implementing Methods• Some methods do not return a value

• Some methods return an output value

public void withdraw(double amount){ double newBalance = balance - amount; balance = newBalance;}

public double getBalance(){ return balance;}

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 understand

Method Call Example•

Set the parameter variable amount to 500 Fetch the balance field of the object whose location is stored in harrysChecking Add the value of amount to balance and store the result in the variable newBalance Store the value of newBalance in the balance instance field, overwriting the old value

harrysChecking.deposit(500);

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 understand

Syntax 3.5: The return Statement

 return expression; or return;

Example: return balance;

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

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 understand

File BankAccount.java01: /**02: A bank account has a balance that can be changed by 03: deposits and withdrawals.04: */05: public class BankAccount06: { 07: /**08: Constructs a bank account with a zero balance.09: */10: public BankAccount()11: { 12: balance = 0;13: }14: 15: /**16: Constructs a bank account with a given balance.17: @param initialBalance the initial balance 18: */

Continued…

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 understand

File BankAccount.java19: public BankAccount(double initialBalance)20: { 21: balance = initialBalance;22: }23: 24: /**25: Deposits money into the bank account.26: @param amount the amount to deposit27: */28: public void deposit(double amount)29: { 30: double newBalance = balance + amount;31: balance = newBalance;32: }33: 34: /**35: Withdraws money from the bank account.36: @param amount the amount to withdraw

Continued…

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 understand

File BankAccount.java37: */38: public void withdraw(double amount)39: { 40: double newBalance = balance - amount;41: balance = newBalance;42: }43: 44: /**45: Gets the current balance of the bank account.46: @return the current balance47: */48: public double getBalance()49: { 50: return balance;51: }52: 53: private double balance;54: }

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 understand

Testing a Class

• Test class: a class with a main method that contains statements to test another class.

• Typically carries out the following steps:

1. Construct one or more objects of the class that is being tested

2. Invoke one or more methods

3. Print out one or more results

Continued…

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 understand

Testing a Class• Details for building the program vary. In

most environments, you need to carry out these steps: 1. Make a new subfolder for your program 2. Make two files, one for each class 3. Compile both files 4. Run the test program

• You can also put two classes into one file (as in the bouncingBall example). However, if you do this, only one class can be delcared public: only one public class is allowed in each file.

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 understand

File BankAccountTester.java01: /**02: A class to test the BankAccount class.03: */04: public class BankAccountTester05: {06: /**07: Tests the methods of the BankAccount class.08: @param args not used09: */10: public static void main(String[] args)11: {12: BankAccount harrysChecking = new BankAccount();13: harrysChecking.deposit(2000);14: harrysChecking.withdraw(500);15: System.out.println(harrysChecking.getBalance());16: }17: }

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 understand

Categories of Variables

• Categories of variables Instance fields (balance in BankAccount) Local variables (newBalance in deposit

method) Parameter variables (amount in deposit

method)

• An instance field belongs to an object

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

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 understand

Categories of Variables

• In Java, the garbage collector periodically reclaims objects when they are no longer used

• Local and parameter variables belong to a method

• Instance fields are initialized to a default value, but you must initialize local variables

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 understand

Lifetime of Variables

harrysChecking.deposit(500);

Continued…

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

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 understand

Lifetime of Variables

Figure 7: Lifetime of Variables Continued…

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 understand

Lifetime of Variables

Figure 7: Lifetime of Variables

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 understand

Implicit and Explicit Method Parameters

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

• The this reference denotes the implicit parameter

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 understand

Implicit and Explicit Method Parameters• Using an instance field name in a method denotes

the instance field of the implicit parameter

public void withdraw(double amount){ double newBalance = balance - amount; balance = newBalance;}

public void withdraw(double amount){ double newBalance = this.balance - amount; this.balance = newBalance;}

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 understand

Implicit and Explicit Method Parameters

• balance is the balance of the object to the left of the dot:

means

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

momsSavings.withdraw(500)

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 understand

Implicit Parameters and this

• Every method has one implicit parameter

• The implicit parameter is always called this

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

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

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 understand

Implicit Parameters and this

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

momsSavings.deposit(500);

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 understand

Implicit Parameters and this

Figure 8:The Implicit Parameter of a Method Call