Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Chapter 3 Implementing Classes

2 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; … }

3 Instance Variables public class Student { private int totalCredits; … } access specifier ( private or public ) type of variable ( int ) name of variable ( totalCredits )

4 public class Counter { private int value; … } Counter concertCounter = new Counter(); Counter boardingCounter = new Counter();

5 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

6 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

7 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

8 Specifying the Public Interface of a Class  Behavior of bank account (abstraction):  deposit money  withdraw money  get balance

9 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());

10 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 }

11 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()

12 Constructor Declaration A constructor initializes the instance variables Constructor name = class name public BankAccount() { // body--filled in later }

13 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

14 Constructor method overloading  Public Student() Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

15 Private variables – hidden to the user of the class Public 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 }

16 BankAccount Public Interface (cont.) Public methods – needed to use an instance of BankAccount We 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 }

17 Class Declaration

18 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));

19 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 }

20 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

21

22

23 Constructors contain instructions to initialize the instance variables of an object: public BankAccount() { balance = 0; } public BankAccount(double initialBalance) { balance = initialBalance; } Implementing Constructors

24 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

25 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

26 Method Declaration syntax

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

28 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; }

29 Implementing Methods public void withdraw(double amount) { balance = balance - amount; } public double getBalance() { return balance; }

30 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 results 4.Print the expected results Continued

31 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

32 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 results 4.Print the expected results

33 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

34 Testing With BlueJ

35 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

36 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 Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

37 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.

38 Local vs. Parameter Variables public class Number{... public void add(int x, int y) { int sum = 0; sum = x + y; this.value = sum; }

39 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.

40 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; }

41 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

42 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

43 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

44 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 } }


Download ppt "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."

Similar presentations


Ads by Google