Top Banner
Chapter 3 Implementing Classes
44

Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Dec 18, 2015

Download

Documents

Winifred Palmer
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Chapter 3

Implementing Classes

Page 2: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Instance Variables

• Instance variables store the data of an object; the fields of an object.

• Instance of a class: an object constructed from the class.

• The class declaration specifies the instance variables:

public class Student{ private int totalCredits; …}

Page 3: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Instance Variables

public class Student

{

private int totalCredits;

}

access specifier (private or public)

type of variable (int)

name of variable (totalCredits)

Page 4: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

public class Counter{

private int value;…

}

Counter concertCounter = new Counter();

Counter boardingCounter = new Counter();

Page 5: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Accessing Private Instance Variables

• The count method advances the counter value by 1:

public void count(){ value = value + 1;}

• The getValue method returns the current value:

public int getValue(){ return value;}

• Private instance variables can only be accessed by methods of the same class

Page 6: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Encapsulation

The process of hiding object data and providing methods for data access declare instance variables as private declare public methods that access the variables

Page 7: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Encapsulation

• Encapsulation allows a programmer to use a class without having to know its implementation

• Information hiding makes it simpler for the implementor of a class to locate errors and change implementations

Page 8: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Specifying the Public Interface of a Class

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

Page 9: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Abstraction – identifying the essential methods of a class or object

•Methods of BankAccount class:

• deposit • withdraw

• getBalance

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

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

Page 10: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Abstraction to Implementation

1. Identify method (deposit money)

2. What is the return type?(nothing)

3. Explicit parameters? (the amount to deposit)

4. Parameter’s data type?(double)

5. public or private?(public)

6. Now, your are ready to implement the method.

1. deposit

2. void deposit

3. void deposit(amount)

4. void deposit(double amount)

5. public void deposit(double amount)

6. public void deposit(double amount) {

// Implementation}

Page 11: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Specifying the Public Interface of a Class

• Method Headers• public void deposit(double amount) • public void withdraw(double amount) • public double getBalance()

• Method Signatures• deposit(double) • withdraw(double) • getBalance()

Page 12: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Constructor Declaration

• A constructor initializes the instance variables

• Constructor name = class name

public BankAccount()

{

// body--filled in later

}

Page 13: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Constructor

• Constructor body is executed when new object is created

• Sets or initializes the internal data of the object that is being constructed

• Constructor method name is always the name of the class

Page 14: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Constructor method overloading

Public Student()

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 15: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Private variables – hidden to the user of the classPublic constructor – needed to create an instance of BankAccount

public class BankAccount { // private variables

double balance

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

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

Page 16: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

BankAccount Public Interface (cont.)

Public methods – needed to use an instance of BankAccountWe do not need to know how the body of each method is implemented.

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

Page 17: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Class Declaration

Page 18: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Using method properly

Given

public void deposit(double amount) public void withdraw(double amount) public double getBalance()

What is wrong with this sequence of statements?

BankAccount harrysChecking = new BankAccount(10000);System.out.println(harrysChecking.withdraw(500));

Page 19: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Commenting the Public Interface

/** Withdraws money from the bank account. @param amount the amount to withdraw */ public void withdraw(double amount) { //implementation filled in later }/** Gets the current balance of the bank account. @return the current balance */ public double getBalance(){ //implementation filled in later }

Page 20: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Class Comment

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

• Provide documentation comments for • every class • every method • every parameter • every return value

Page 21: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.
Page 22: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.
Page 23: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

• Constructors contain instructions to initialize the instance variables of an object:

public BankAccount() { balance = 0; }

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

Implementing Constructors

Page 24: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

• Statement:

BankAccount harrysChecking = new BankAccount(1000);

• Create a new object of type BankAccount

• Call the second constructor (because an explicit parameter 1000 is supplied in the constructor call)

• The construcor sets the private field variable balance to 1000

Constructor Call Example

Page 25: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

• Statement:

BankAccount harrysChecking = new BankAccount(1000);

• New Creates a new object using the Constructor, the object truly resides somewhere in memory (RAM)

• Then assign harrysChecking to point to that object, i.e., harrysChecking is a variable that references an instance of the BankAccount class

Constructor Call Example

Page 26: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Method Declaration syntax

Page 27: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Implementing Methods

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

Page 28: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Calling Methods from a main program

harrysChecking.deposit(500); • Set the parameter variable amount to 500

• Fetch the balance variable of the object whose location is stored in harrysChecking

• Add the value of amount to balance

• Store the sum in the balance instance variable, overwriting the old

value

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

Page 29: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Implementing Methods

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

• public double getBalance() { return balance; }

Page 30: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Unit Testing

• Unit test: Verifies that a class works correctly in isolation, outside a complete program

• To test a class, use an environment for interactive testing, or write a tester class

• Tester 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 results4. Print the expected results

Continued

Page 31: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Unit Testing

• Unit test: Verifies that a class works correctly in isolation, outside a complete program

• To test a class, use an environment for interactive testing, or write a tester class

• Tester class: A class with a main method that contains statements to test another class

Continued

Page 32: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Unit Testing

• 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 results4.Print the expected results

Page 33: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

1 /** 2 A class to test the BankAccount class. 3 */ 4 public class BankAccountTester 5 { 6 /** 7 Tests the methods of the BankAccount class. 8 @param args not used 9 */ 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 System.out.println("Expected: 1500"); 17 } 18 } Program Run:

1500 Expected: 1500

Page 34: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Testing With BlueJ

Page 35: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Local Variables vs. Instance Variables

• Local and parameter variables belong to a method

• When a method or constructor runs, its local and parameter variables come to life

• When the method or constructor exits, they DIE!

• Instance variables belong to objects, not methods

• When an object is constructed, its instance variables are created

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

Page 36: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Local vs. Instance Variables

public class Student {Private double qualityPoints;Private int totalCredits;…public double calculateGPA() {

double gpa = 0;if (totalCredits != 0)

gpa = qualityPoints/totalCredits;return gpa;

}

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 37: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Garbage Collection

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

• Specifically, the memory is freed-up so other objects can reclaim the memory space.

• Complex programs may use up all the memory, so freeing up memory is important.

Page 38: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Local vs. Parameter Variables

public class Number{

...

public void add(int x, int y) {

int sum = 0;

sum = x + y;

this.value = sum;

}

Page 39: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Local vs. Parameter Variables

Both Local and Parameter variables belong to methods They come alive when the method is called They die when the method exits.

They differ in their initialization. Parameter variables are initialized with the call values Local variables must be explicitly initialized.

Page 40: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Local vs. Parameter Variables

Parameter variables are initialized with the call values

Number myNumber = new Number();

myNumber.add(10, 15);

Local variables must be explicitly initialized. int sum = 0;

public class Number{...

public void add(int x, int y) {int sum = 0;sum = x + y;this.value = sum;

}

Page 41: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Implicit Parameter

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

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

• In the call

momsSavings.deposit(500)

The implicit parameter is momsSavings and the explicit parameter is 500

• When you refer to an instance variable inside a method, it means the instance variable of the implicit parameter

Page 42: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Implicit Parameters and this

• The this reference denotes the implicit parameter

balance = balance + amount;

actually means

this.balance = this.balance + amount;

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

Page 43: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Implicit Parameters and this

• A method call without an implicit parameter is applied to the same object

• Example:

public class BankAccount{ . . . public void monthlyFee() { withdraw(10); // Withdraw $10 from this account

}}

• The implicit parameter of the withdraw method is the (invisible) implicit parameter of the monthlyFee method

Page 44: Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.

Implicit Parameters and this

• You can use the this reference to make the method easier to read:

public class BankAccount{ . . . public void monthlyFee() { this.withdraw(10); // Withdraw $10 from this account

}}