Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter 9 A Second Look at Classes and Objects - 4."— Presentation transcript:

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

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

3 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 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 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 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 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 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 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 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 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 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 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 } 0 1 2 3 45 6

14 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 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 16 II. Enumerated Types

17 17

18 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 19 II. Enumerated Types

20 20 Checkpoint 9.5 9.6 9.7

21 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 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 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 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 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 26 Stock Purchase Problem UML Class Diagram

27 27 Stock Purchase Problem

28 28

29 29

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


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

Similar presentations


Ads by Google