COMP 110 Some more about objects and references Luv Kohli October 10, 2008 MWF 2-2:50 pm Sitterson 014
Announcements Midterm will not cover any new material discussed after today’s class, except for Lab 5 and today’s in-class exercise Ivan Sutherland talk on Monday, 4pm, Sitterson Hall 011 2
Questions? 3
Today in COMP 110 DecimalFormat Some more about objects and references 4
DecimalFormat import java.text.DecimalFormat; DecimalFormat df = new DecimalFormat(“0.00”); double number = ; System.out.println(df.format(number)); Output: “0.00” is the pattern that the format method will use to format its output ◦ Two digits after the decimal point, one digit before (but it will display all digits if more than one before) Fractional portion will be rounded 5
DecimalFormat DecimalFormat’s format method returns a StringBuffer, not a String, but you can still print out a StringBuffer See Appendix 6 (4 th edition) or Appendix 4 (5 th edition) for many more details Experiment with it on your own 6
Variables of a class type Contain the memory address of the object named by the variable ◦ NOT the object itself Object is stored in some other location in memory The address to this other location is called a reference to the object Class types are also called reference types 7
Writing the.equals() method public class Book { private String name; private int page; public boolean equals(Book book) { return (this.name.equals(book.name) && this.page == book.page); } 8 Not quite the right way to write the equals method but okay for now
.equals() Every class has a default.equals() method if it is not explicitly written ◦ Does not necessarily do what you want You decide what it means for two objects of a specific class type to be considered equal ◦ Perhaps books are equal if the names and page numbers are equal ◦ Perhaps only if the names are equal ◦ Put this logic inside.equals() method 9
Parameters of a primitive type public void increaseNum(int num) { num++; } public void doStuff() { int x = 5; increaseNum(x); System.out.println(x); } Prints 5. Why? num is local to increaseNum method; does not change x 10
Parameters of a class type public void changeBook(Book book) { book = new Book(“Biology”); } public void doStuff() { Book jacksBook = new Book(“Java”); changeBook(jacksBook); System.out.println(jacksBook.getName()); } Prints Java. Why? book is local to changeBook, does not change jacksBook 11
Parameters of a class type public void changeBook(Book book) { book.setName(“Biology”); } public void doStuff() { Book jacksBook = new Book(“Java”); changeBook(jacksBook); System.out.println(jacksBook.getName()); } Prints Biology. Why? book contains the same address as jacksBook! 12
Monday 13