CS1101: Programming Methodology http://www.comp.nus.edu.sg/~cs1101x/ Aaron Tan How was your mid-term test? Which of the following best describes your feeling about the test? 2 This is Week 8 Week 7: Revision on Modular programming Chapter 6: Object-Oriented Programming Chapter 7: OOP Additional Details Survey This week: Chapter 7: OOP Additional Details (cont.) About String Exercises Chapter 8: Software Engineering Chapter 9: Classes with Class Members Exercises 3 Chapter 7 OOP Additional Details Let’s continue chapter 7 from where we left off last week… 4 Writing good programs Now that we know basic programming, we should not be contended with merely writing correct programs. We have to write good programs By following good programing practice and methodology By writing elegant and efficient programs (this requires more practice and is the subject for follow-up modules, but no harm starting early!) 5 Overloaded Constructors Refer to Fraction.java in the textbook. We can write more constructors. Examples: public Fraction( ) { this(0, 1); // creates a fraction 0/1 } New public Fraction(Fraction frac) { this(frac.numerator, frac.denominator); // copies frac } public Fraction(int n) { this(n, 1); // creates a fraction n/1 } Given public Fraction(int n, int d) { this.numerator = n; this.denominator = d; this.quotient = (double) this.numerator / this.denominator; } 6 String class After the tracing exercises last week, some students tried question 4 on strings, and found that the result doesn’t match my explanation. Why? The reason is that String is a very special class. Example: We do not need the “new” statement to create a String object! 7 String is immutable In Java, a String object is immutable This means once a String object is created, it cannot be changed, such as replacing a character with another character or removing a character The String methods we have used so far do not change the original string. They create a new string from the original. For example, substring creates a new string from a given string. The String class is defined in this manner for efficiency reason. 8 Effect of Immutability We can do this because String objects are immutable. 9 String: Examples Example 1: String s = "abc"; s = s + "def"; new string "abcdef" is created for s in the second statement. Example 2: A String s1 = "abc"; String s2 = "abc"; s1 = "xyz"; s2 still refers to "abc". (Imagine the horror if this is not so!) Hence, strings behave differently from what I explained last week, about reference variable of an object or an array. 10 Class Activity: Ball class Last week, we created a Ball class with these members: Instance variables (data members) colour (String) radius (double) Methods: constructors, accessors and mutators Overloaded constructors: Ball() and Ball(String, double) Accessors: getColour() and getRadius() Mutators: setColour(String) and setRadius(double) Let’s download the files Ball.java and BallDriver.java and study them 11 Ball: Writing equals() method Run BallDriver and enter the same data for both objects myBall1 and myBall2 What is the truth value of (myBall1 == myBall2)? Why is it so? The equals() method isn’t working because we haven’t written it! Write the equals() method. Where should it be? In Ball.java or BallDriver.java? Write the equals() method now. 12 Ball: Writing toString() method (1/2) The following is a possible output of the program: 1st ball: [blue, 2.5] 2nd ball: [orange, 3.1] Can you replace the output statements in BallDriver.java with the following? System.out.print("1st ball: "); System.out.println(myBall1); System.out.print("2nd ball: "); System.out.println(myBall2); What’s the output? (Actual output may differ from below.) 1st ball: Ball@471e30 2nd ball: Ball@10ef90c Hashcodes (page 514) 13 Ball: Writing toString() method (2/2) To make it work, you need to write the toString() method. The toString() method returns a string, which is the string representation of the data in an object. Note that after the toString() method is written, you may print myBall1 object in any of these two ways: System.out.println( myBall1 ); or System.out.println( myBall1.toString() ); Write the toString() method now. 14 Modularisation (1/2) Observe that there are duplicate codes in the input section of BallDriver.java. The blue statements and red statements are almost the same. If we need to create more Ball objects, the code gets even longer. System.out.print("Enter 1st ball's colour: "); colour = stdIn.next(); System.out.print("Enter 1st ball's radius: "); radius = stdIn.nextDouble(); Ball myBall1 = new Ball(colour, radius); System.out.print("Enter 2nd ball's colour: "); colour = stdIn.next(); System.out.print("Enter 2nd ball's radius: "); radius = stdIn.nextDouble(); Ball myBall2 = new Ball(colour, radius); 15 Modularisation (2/2) Can you ‘modularise’ your BallDriver.java program so that you call a method each time you want to create a Ball object? You can then replace the code in the previous slide with this: Ball myBall1 = readBall(stdIn, "1st"); Ball myBall2 = readBall(stdIn, "2nd"); You need to write the readBall() method. 16 Chapters 8 and 9 We’ll take a break from the Ball class and return to it later. Let’s go to Chapters 8 and 9 now. 17 Point class (1/3) I want to introduce the Point class to you because… it appears quite often in past year’s papers I want to add an instance variable for a Point object inside the Ball class (so that we have an object within an object) Refer to API: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Point.html Field Summary int x int y The x coordinate. The y coordinate. Constructor Summary Point() Constructs and initializes a point at the origin (0, 0) of the coordinate space. Point(int x, int y) Constructs and initializes a point at the specified (x, y) location in the coordinate space. Point(Point p) Constructs and initializes a point with the same location as the specified Point object. 18 Point class (2/3) Method Summary boolean equals(Object obj) Determines whether or not two points are equal. Point getLocation() Returns the location of this point. double getX() Returns the X coordinate of the point in double precision. double getY() Returns the Y coordinate of the point in double precision. void move(int x, int y) Moves this point to the specified location in the (x, y) coordinate plane. void setLocation(double x, double y) Sets the location of this point to the specified double coordinates. void setLocation(int x, int y) Changes the point to have the specified location. void setLocation(Point p) Sets the location of the point to the specified location. String toString() Returns a string representation of this point and its location in the (x, y) coordinate space. This is not a complete list. Refer to the API page. 19 Point class (3/3) Let’s do some programs on Point class so that you are familiar with it. Download PointDriver.java and study it. Note how a Point object is displayed. Now, let’s do something more complex. Download MyRectangle.java, MyRectangleDriver.java and MyRectangleDriverV2.java and study them. The computeArea() method in MyRectangle.java is a stub. Complete it. Should we make area another data member of the MyRectangle class? Think about it. If we do make it a data member, what changes do we need to make in MyRectangle.java? We’ll discuss this next week. 20 Other Point related classes Check out other related classes on the API Point2D.Double Point2D.Float 21 Ball class: centre (1/2) Now that we understand the Point class, let’s include a new data member for the Ball class centre: of type Point, to represent the centre of a Ball object Centre is supposed to be a 3D point, since balls are 3D objects, but some students are frightened of 3D, so we shall just make centre a 2D point You need to update/add constructors,add appropriate accessor and mutator methods, and update the toString() method in Ball.java. 22 Ball class: centre (2/2) In your BallDriver.java program, create two Ball objects, and check whether they overlap each other. (Two balls overlap when their centres are too close to each other.) You need to add an appropriate method to do the above. What should be the name of the method? Where should that method be, in Ball.java or BallDriver.java? What is its return type? What is/are its parameter(s)? This is your take-home exercise 23 Next week Next week, I will present BallV2.java and BallV2Driver.java that include all the things we’ve discussed today 24 Announcement/Reminder Lab #3 Deadline: 8 October (Wednesday), 2359hr. Identical codes Please do not share codes for your lab assignments! Mid-term test Results will be released on the IVLE gradebook. Watch out for the announcement. Your answer sheets will be returned to you next week in your discussion session. 25 This is Week 8 Next week? Chapter 10 Arrays and ArrayList(sections 10.7 – 10.14) 26 End of file 27