Chapter 9 A Second Look at Classes and Objects - 4.

Slides:



Advertisements
Similar presentations
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Advertisements

Chapter 3 DATA: TYPES, CLASSES, AND OBJECTS. Chapter 3 Data Abstraction Abstract data types allow you to work with data without concern for how the data.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
9-1 Chapter.8 Classes & Objects: A deeper look –Static Class Members –Passing & Returning Objects from Methods –The toString method –Writing an equals.
Chapter 8: A Second Look at Classes and Objects
More methods and classes, 4 of 4 Math 130 Introduction to Programming Lecture # 18 Monday, October 8, 2007.
© 2010 Pearson Addison-Wesley. All rights reserved. 9-1 Chapter Topics Chapter 9 discusses the following main topics: –Static Class Members –Passing Objects.
Java Software Solutions
Road Map Introduction to object oriented programming. Classes
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
9-2  Static Class Members  Passing Objects as Arguments to Methods  Returning Objects from Methods  The toString method  Writing an equals Method.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes: Cooper & Ji & Varol Fall 09.
Chapter 8: Arrays.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 9 – Part Tony Gaddis Modified by Elizabeth Adams.
 Constructor  Finalize() method  this keyword  Method Overloading  Constructor Overloading  Object As an Argument  Returning Objects.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CONTENTS Wrapper Class Enumeration Garbage Collection Import static.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Starting Out With Java Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 9 Slide #1 Review.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
Chapter 8 Arrays and the ArrayList Class Arrays of Objects.
Chapter 9 A Second Look at Classes and Objects - 2.
SCJP 5, 1/7 Declarations, Initialization and Scoping
More About Objects and Methods
Chapter 3 Control Statements
JAVA MULTIPLE CHOICE QUESTION.
11 Chapter Structured Data
Elementary Programming
Java Primer 1: Types, Classes and Operators
Topics Static Class Members Overloaded Methods Overloaded Constructors
A Second Look at Classes and Objects - 2
Road Map Introduction to object oriented programming. Classes
Java Review: Reference Types
Enumerated DATA Types Enum Types Enumerated Data Types
Chapter 9: A Second Look at Classes and Objects
Chapter 9: A Second Look at Classes and Objects
Chapter 3 Introduction to Classes, Objects Methods and Strings
(and a review of switch statements)
(and a review of switch statements)
Unit-1 Introduction to Java
Chapter 11: Structured Data.
Pointers C#, pointers can only be declared to hold the memory addresses of value types int i = 5; int *p; p = &i; *p = 10; // changes the value of i to.
A Different Kind of Variable
Today’s topics UML Diagramming review of terms
More About Objects and Methods
Chap 1 Chap 2 Chap 3 Chap 5 Surprise Me
Enumerated DATA Types Enum Types Enumerated Data Types
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Object Oriented Programming in java
Classes, Objects and Methods
Dr. Sampath Jayarathna Cal Poly Pomona
Standard Version of Starting Out with C++, 4th Edition
TCSS 143, Autumn 2004 Lecture Notes
OO Programming Concepts
Variables and Constants
Presentation transcript:

Chapter 9 A Second Look at Classes and Objects - 4

2 Contents I. The this Reference Variable II. Enumerated Types III. Garbage Collection IV. Focus on Object Oriented Design Class Collaboration

3 I. The this Reference Variable The this keyword is the name of a reference variable that an object can use to refer to itself. It is available to all non-static methods. public boolean equals(Stock object2) { boolean status; //Determine whether this object's //symbol and sharePrice fields are //equal to object2's symbol and //sharePrice fields. if(symbol.equals(object2.symbol) && sharePrice == object2.sharePrice) status = true; else status = false; return status; } if(this.symbol.equals(object2.symbol) && this.sharePrice == object2.sharePrice)

4 I. The this Reference Variable Using this to Overcome Shadowing One common use of the this keyword is to overcome the shadowing of a field name by a parameter name. The parameter name shadows the field name if the parameter has the same name as a field. public Stock(String sym, double price) { symbol = sym; sharePrice = price; } public Stock(String symbol, double sharePrice) { this.symbol = symbol; this.sharePrice = sharePrice; }

5 I. The this Reference Variable Using this to Call an Overloaded Constructor from Another Constructor A constructor is automatically called when an object is created. We can not call a constructor explicitly. There is one exception to this rule: We can use the this keyword to call one constructor from another constructor in the same class.

6 I. The this Reference Variable The Stock class has the following constructor: public Stock(String sym, double price) { symbol = sym; sharePrice = price; } Let's suppose that we also want a constructor that only accepts an argument for the symbol field and assign 0.0 to the sharePrice field. Here's one way to write the constructor: public Stock(String sym) { this(sym, 0.0); } This constructor uses the this variable to call the first constructor.

7 I. The this Reference Variable Remember the following rules about using this to call a constructor: this can only be used to call a constructor from another constructor in the same class. It must be the first statement in the constructor that is making the call. If it is not the first statement, a compiler error will result.

8 II. Enumerated Types A data type defines the values that are legal for any variables of that data type. An enumerated data type consists of a set of predefined values. We can use the data type to create variables that can hold only the values that belongs to the enumerated data type. For example, we want to create a data type named Day, and the legal values were the names of days of week ( Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday )

9 II. Enumerated Types Creating an enumerated data type: enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } enum : The keyword is used to declare an enumerated data type Day : The name of the enumerated data type SUNDAY, MONDAY, TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY: enum constants. When making up names for enum constants, it is not required that they be written in all uppercase letters. However, the standard convention is to write them in all uppercase letters.

10 II. Enumerated Types Using enumerated data type: Day workDay; // Declares workDay as a variable // of the Day type. workDay = Day.WEDNESDAY; Enumerated types are specialized classes. When we write an enumerated type declaration, we are actually creating a special kind of class. enum constants are actually objects of the class. We can write an enumerated type declaration inside its own file. The filename must match the name of the type.

11 II. Enumerated Types enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } Day workDay; workDay = Day.WEDNESDAY; address Day.SUNDAY Day.MONDAY Day.TUESDAY Day.WEDNESDAY Day.THURSDAY Day.FRIDAY Day.SATURDAY The workDay variable holds the address of the Day.WEDNESDAY object. Each of these is an object of the Day type, which is a specialized class.

12 II. Enumerated Types enum constants, which are actually objects, come automatically equipped with a few methods: toString() : returns the name of the calling enum constant as a string. //This code displays WEDNESDAY Day workDay = Day.WEDNESDAY; System.out.println(workDay); //This code also displays WEDNESDAY System.out.println(Day.WEDNESDAY);

13 II. Enumerated Types ordinal() : returns an integer value representing the constant's ordinal value. The constant's ordinal value is its position in the enum declaration, with the first constant being at position 0. enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

14 II. Enumerated Types //This code displays 5 and 1 Day lastWorkDay = Day.FRIDAY; System.out.println(lastWorkDay.ordinal()); System.out.println(Day.MONDAY.ordinal()); equals() : accepts an object as its argument and returns true if that object is equal to the calling enum constant. Day myDay = Day.TUESDAY; if(myDay.equals(Day.TUESDAY)) System.out.println(“They are the same”);

15 II. Enumerated Types compareTo() : compares enum constants of the same type. It accepts an object as its argument and returns the following: a negative integer value if the calling enum constant's ordinal value is less than the argument's ordinal value zero if the calling enum constant is the same as the argument a positive integer value the calling enum constant's ordinal value is greater than the argument's ordinal value Day myDay = Day.FRIDAY; if(myDay.compareTo(DAY.MONDAY) > 0) System.out.println(myDay + “ is greater than “ + Day.MONDAY);

16 II. Enumerated Types

17

18 II. Enumerated Types Switching on an enumerated type Java allows you to test an enum constant with a switch statement. In the case statement, the enumerated constant are not fully qualified. The fully qualified name of Day type's WEDNESDAY constant is : Day.WEDNESDAY

19 II. Enumerated Types

20 Checkpoint

21 III. Garbage Collection When an object is no longer needed, it should be destroyed so the memory it used can be freed for other purpose. We do not have to destroy objects after we are finished using them. The Java Virtual Machine periodically runs a process known as the garbage collection, which removes unreferenced objects from memory.

22 III. Garbage Collection Look at the following code: //Declare two BankAccount reference variable BankAccount account1, account2; //Create an object and reference it with account1 account1 = new BankAccount(500.0); //Reference the same object with account2 account2 = account1; //Store null in account1 so it no longer references the object account1 = null; //The object is still referenced by account2. //Store null in account2 so it no longer references the object. account2 = null; //Now the object is no longer referenced, //so it can be removed by the garbage collector.

23 III. Garbage Collection If a class has a method named finalize, it is called automatically just before an object is destroyed by the garbage collector. If we wish to execute code just before an object is destroyed, we create a finalize method in the class and place the code there. The finalize method accepts no arguments and has a void return type. The garbage collector runs periodically, and we cannot predict exactly when it will execute. Therefore, we cannot know exactly when an object's finalize method will execute.

24 IV. Focus on Object Oriented Design Class Collaboration It is common for classes to interact, or collaborate, with each other to perform their operations. Part of the object-oriented design process is identifying the collaborations among classes. If one object is to collaborate with another object, then it must know something about the other object's class methods and how to call them.

25 IV. Focus on Object Oriented Design Class Collaboration Stock purchase problem A stock purchase consists of info of a stock and number of shares Info of a stock includes the trading symbol and share price Trading symbol is a short series of characters that are used to identify the stock on the stock exchange Develop a program to calculate the cost of a stock purchase, given that cost = number-of shares × share-price

26 Stock Purchase Problem UML Class Diagram

27 Stock Purchase Problem

28

29

30 Stock Purchase Problem This code allows us to purchase shares of XYZ company's stock: Stock xyzCompany = new Stock(“XYZ”, 9.62); //Create a StockPurchase object for the transaction StockPurchase buy = new StockPurchase(xyzCompany, 100); //Display the cost of the transaction System.out.println(“Cost of the stock: $” + buy.getCost());