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.

Slides:



Advertisements
Similar presentations
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Advertisements

Chapter 8 – Interfaces and Polymorphism Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Part I. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
I NHERITANCE Chapter 10. I NHERITANCE Mechanism for enhancing existing classes You need to implement a new class You have an existing class that represents.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
Our BankAccount class should define three methods  deposit  withdraw  getBalance How a programmer will carry out these operations?  We assume that.
Chapter 13 Inheritance. An Introduction to Inheritance Inheritance: extend classes by adding methods and fields (variables) Example: Savings account =
Chapter 3: Implementing Classes Part 1. To become familiar with the process of implementing classes To be able to implement simple methods To understand.
CHAPTER 11 INHERITANCE CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Function Overloading Having more than one function with the same name. list of argument of a function are called signature of a function. We can have more.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 2 – An Introduction to Objects and Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
The Java Programming Language  Simple – but abstract  Safe  Platform-independent ("write once, run anywhere")  Has a Rich growing library  Designed.
CHAPTER 2 OBJECTS AND CLASSES Goals: To understand the concepts of classes and objects To realize the difference between objects and object references.
Datalogi A 2: 15/9. Java Slides based on Horstmann chapter 2&3 Objects and classes Import, methods, references Implementing a class.
Chapter 3 Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To understand.
Using Objects Object: an entity in your program that you can manipulate Attributes Methods Method: consists of a sequence of instructions that can access.
Chapter 3  Implementing Classes 1 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.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object-Oriented Programming
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Inheritance.
Often categorize concepts into hierarchies: Inheritance Hierarchies Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Three: Implementing Classes.
Classes CS 21a: Introduction to Computing I First Semester,
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
Chapter 3 Implementing Classes. Assignment Read 3.1 – 3.5 and take notes complete Self Check Exercises 1-10; Due September 24 th Read 3.6 – 3.8 and take.
Chapter 3 – Implementing Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
ICOM 4015: Advanced Programming Lecture 3 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Three:
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
CHAPTER 11 INHERITANCE. CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 2 – An Introduction to Objects and Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Fall 2006Slides adapted from Java Concepts companion slides1 Implementing Classes Advanced Programming ICOM 4015 Lecture 3 Reading: Java Concepts Chapter.
Encapsulation ◦ Blackbox concept Data and method(s) Hidden details InterfaceEffect(s) methods called class.
INFSY 535.  Small systems  Larger systems 1.Understand the program requirement- what 3. Write and test each part (unit testing) 4. Maintenance 2. Specify.
CSH Intro. to Java. The Big Ideas in Computer Science Beyond programming Solving tough problems Creating extensible solutions Teams of “Computational.
Chapter 2 – An Introduction to Objects and Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 3: An Introduction to Classes 1 Chapter 3 An Introduction to Classes.
Chapter 3: Implementing Classes Part 1. To become familiar with the process of implementing classes To be able to implement simple methods To understand.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 3 Implementing Classes
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 3 – Implementing Classes.
Chapter Goals To become familiar with the process of implementing classes To be able to implement and test simple methods To understand the purpose and.
Chapter 3 – Implementing Classes
Lecture 3 John Woodward.
Data Structures and Algorithms revision
Chapter 3 – Implementing Classes
Chapter Three: Implementing Classes
Implementing Classes Yonglei Tao.
Chapter Goals To become familiar with the process of implementing classes To be able to implement and test simple methods To understand the purpose and.
Chapter Three - Implementing Classes
Chapter Three - Implementing Classes
Chapter 3 Implementing Classes
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
JAVA CLASSES.
AN INTRODUCTION TO OBJECTS AND CLASSES
Classes CS 21a: Introduction to Computing I
Introduction to Object-Oriented Programming
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

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 constructed from the class. The class declaration specifies the instance variables: public class Student { private int totalCredits; … }

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

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

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

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

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

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

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

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 }

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

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

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

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

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 }

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 }

Class Declaration

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

Commenting the Public Interface /** Withdraws money from the bank amount the amount to withdraw */ public void withdraw(double amount) { //implementation filled in later } /** Gets the current balance of the bank the current balance */ public double getBalance() { //implementation filled in later }

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

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

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

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

Method Declaration syntax

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

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

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

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

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

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

1 /** 2 A class to test the BankAccount class. 3 */ 4 public class BankAccountTester 5 { 6 /** 7 Tests the methods of the BankAccount class. 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

Testing With BlueJ

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

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.

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.

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

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.

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

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

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

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

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