Implementing Classes Yonglei Tao.

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

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 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 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.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Inheritance Part III. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke.
CHAPTER 2 OBJECTS AND CLASSES Goals: To understand the concepts of classes and objects To realize the difference between objects and object references.
1 Classes and Objects Overview l Classes and Objects l Constructors l Implicit Constructors l Overloading methods this keyword l public, private and protected.
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.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
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.
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,
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.
Classes All Java code must be inside classes Class types – Utility classes Used to store constants, utility methods, etc. – Driver classes – Abstract Data.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A class represents a single concept from the problem domain Name.
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.
1 Warm-Up Problem Just like with primitive data types (int, double, etc.), we can create arrays of objects. ex: bankAccount employees[100]; Problem: It’s.
Classes: Member Functions and Implementation November 22, 2002 CSE103 - Penn State University Prepared by Doug Hogan.
ICOM 4015: Advanced Programming Lecture 3 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Three:
Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.
CHAPTER 11 INHERITANCE. CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
ACM/JETT Workshop - August 4-5, : Defining Classes in Java.
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.
Bank Account Example public class BankAccount { private double balance; public static int totalAccounts = 0; public BankAccount() { balance = 0; totalAccounts++;
Chapter 9 – Designing Classes Goals Learning to design classes Learning to design classes Preconditions and postconditions for methods Preconditions.
©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 9 – Designing Classes. Chapter Goals Discovering and learning to Design classes Discovering and learning to Design classes Preconditions and postconditions.
Chapter 3 Implementing Classes
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 3 – Implementing Classes.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
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
Java OOP Overview Classes and Objects, Members and Class Definition, Access Modifier, Encapsulation Java OOP Overview SoftUni Team Technical Trainers.
Chapter Three: Implementing Classes
Lecture Notes – Inheritance (Ch 9-10)
suggested reading: Java Ch. 6
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
د.سناء الصايغ الفصل الأول البرمجة الشيئية
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
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Implementing Classes Yonglei Tao

Public Interface of Class Counter /** This class models a tally counter. */ public class Counter { … public Counter() { … } public int getValue() { … } public void count() { … } }

Using a Class Counter tally = new Counter(); tally.count(); int result = tally.getValue();

Instance Variables Instance variables should be declared as private public class Counter { private int value; … } Instance variables should be declared as private

Instance Variables (cont.)

Constructors /** This class models a tally counter. */ public class Counter { private int value; Initialize a newly created Counter object. A default constructor. public Counter() { value = 0; }

Overloaded Constructors public Counter(int init) { value = init; } public Counter(Counter other) { value = other.value; … Counter counter1 = new Counter(); Counter counter2 = new Counter(5); Counter counter3 = new Counter(counter2); Counter counter4 = new Counter(new Counter(10)); Create a copy of counter2

Methods of a Class /** This class models a tally counter. */ public class Counter { private int value; Gets the current value of this counter. @return the current value public int getValue() { return value; }

Methods of a Class (cont.) /** Advances the value of this counter by 1. */ public void count() { value = value + 1; }

Discussion Private instance variables can only be accessed by methods of the same class How to allow the client to reset a counter back to zero? public void reset() How to make Counter do countdown also? public void countdown()

Object-Oriented Programming We need to represent a bank account in an application under development Its expected behaviors include deposit money withdraw money get balance

Specify the Public Interface Methods of class Account deposit withdraw getBalance In order to support method calls such as harrysChecking.deposit(2000); harrysChecking.withdraw(500); System.out.println(harrysChecking.getBalance());

Method Declaration access specifier return type method name public void deposit (double amount) { . . . } public void withdraw (double amount) { . . . } public double getBalance () { . . . } access specifier return type method name list of parameters method body

Constructor Declaration public BankAccount() { // body } public BankAccount (double initBalance) {

Public Interface for Class Account public class BankAccount { // private variables public BankAccount() { // body } public BankAccount (double initialBalance) {

Public Interface for Account (cont.) public void deposit(double amount) { // body } public void withdraw(double amount) { public double getBalance() {

Commenting the Public Interface /** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { … Constructs a bank account with a zero balance. public BankAccount() { … } Constructs a bank account with a given balance. @param initialBalance the initial balance public BankAccount(double initialBalance) { … }

Commenting the Public Interface (cont.) /** 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 }

Declaring Instance Variable public class BankAccount { private double balance; … }

Implementing Constructors public BankAccount () { balance = 0; } public BankAccount (double initialBalance) { balance = initialBalance; BankAccount harrysChecking = new BankAccount(1000);

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

BankAccount.java 1 /** 2 A bank account has a balance that can be changed by 3 deposits and withdrawals. 4 */ 5 public class BankAccount 6 { 7 private double balance; 8 9 /** 10 Constructs a bank account with a zero balance. 11 */ 12 public BankAccount() { 14 balance = 0; 15 } 16 17 /** 18 Constructs a bank account with a given balance. 19 @param initialBalance the initial balance 20 */ 21 public BankAccount(double initialBalance) { 23 balance = initialBalance; 24 }

BankAccount.java (cont.) 26 /** 27 Deposits money into the bank account. 28 @param amount the amount to deposit 29 */ 30 public void deposit(double amount) { 32 balance = balance + amount; 33 } 35 /** 36 Withdraws money from the bank account. 37 @param amount the amount to withdraw 38 */ 39 public void withdraw(double amount) { 41 balance = balance - amount; 42 } 44 /** 45 Gets the current balance of the bank account. 46 @return the current balance 47 */ 48 public double getBalance() { 50 return balance; 51 } 52 }

Discussion How can you use the methods of the public interface to empty the tomsChecking bank account? tomsChecking.withdraw( tomsChecking.getBalance() ) Suppose you also want the ability to keep track of an account number in addition to the balance. What would you change the public interface to accommodate this enhancement? Add an accountNumber parameter to the constructors Add a getAccountNumber method No need for a setAccountNumber method – the account number never changes after construction Add an instance variable to store the number

Local Variables public void withdraw (double amount) { double newBalance = balance - amount; if ( newBalance <= 0 ) return; balance = newBalance; }

Scope of Local Variables public class RectangleTester { public static double area(Rectangle rect) { double r = rect.getWidth() * rect.getHeight(); return r; } public static void main(String[] args) { Rectangle r = new Rectangle(5, 10, 20, 30); double a = area(r); System.out.println(r); } }

Scope of Local Variables if (x >= 0) { double r = Math.sqrt(x); ... } // Scope of r ends here else { Rectangle r = new Rectangle(5, 10, 20, 30); // OK - it is legal to declare another r here ... }

Overlapping Scope Which one to refer to if using value in this method? public class Coin { ... public double getExchangeValue(double exchangeRate) { double value; ... return value; } private String name; private double value; } Which one to refer to if using value in this method? How to refer to instance variable value in this method?

Built-in Reference this How does Java ensure that the proper object is referenced? public void deposit(double amount) { balance = balance + amount; } TomsSavings.deposit(500) MarksSavings.deposit(500) Keyword this refers to the current object, that is, the one on which the method is invoked In method deposit(), balance is an instance variable but which object it belongs to? How does Java know since there is only one copy of the code for method amount.

Built-in Reference this (cont.) An instance variable in a method belongs to the object the this reference refers to automatically In other words balance = balance + amount; actually means this.balance = this.balance + amount; The same is true for a method call such as public class BankAccount { . . . public void monthlyFee() { withdraw(10); // withdraw $10 from this account }

Built-in Reference this (cont.) public class MyClass { private int id; private String name; public MyClass (int id, String name) { this.id = id; this.name = name; } …

Local Variables vs. Instance Variables What are their differences? Lifetime Scope Initialization