CS 1101 Programming Methodology http www comp nus

  • Slides: 47
Download presentation
CS 1101: Programming Methodology http: //www. comp. nus. edu. sg/~cs 1101/

CS 1101: Programming Methodology http: //www. comp. nus. edu. sg/~cs 1101/

Week 7: Defining Your Own Classes – Part 2 § Previous lecture: § Chapter

Week 7: Defining Your Own Classes – Part 2 § Previous lecture: § Chapter 6: Repetition Statements (cont’d) § Writing Modular Programs § Testing and Debugging § This week: § Chapter 7: Defining Your Own Classes – Part 2 § Next week: § Chapter 9: Characters and Strings § Chapter 10: Arrays and Collections © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 2

Welcome Back! § ARE YOU ENERGISED? © CS 1101 (AY 2009 -2010 Semester 1)

Welcome Back! § ARE YOU ENERGISED? © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 3

Master. Mind n n Have you completed your program? Show it to us! ©

Master. Mind n n Have you completed your program? Show it to us! © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 4

Chapter 7 n Let’ go over Thomas Wu’s slides now… © CS 1101 (AY

Chapter 7 n Let’ go over Thomas Wu’s slides now… © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 5

Method Invocation (1/3) n Given the following public void set. Radius(double r) { …

Method Invocation (1/3) n Given the following public void set. Radius(double r) { … } public static void main(String[] args) { … ball. set. Radius(s); } n n n r is called the formal parameter s is the actual parameter Pass-by-value: The value of s is copied into r. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 6

Method Invocation (2/3) n n Actual parameters provide information that is otherwise unavailable to

Method Invocation (2/3) n n Actual parameters provide information that is otherwise unavailable to a method When a method is invoked q q q Java sets aside memory for that particular invocation, called the activation record Activation record stores, among other things, the values of the formal parameters Formal parameters initialized with the values of the actual parameters After initialization, the actual parameters and formal parameters are independent of each other Flow of control is transferred temporarily to that method © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 7

Method Invocation (3/3) n Java divides the memory allocated to a program into two

Method Invocation (3/3) n Java divides the memory allocated to a program into two portions: stack and heap. q q Activation records are maintained in the stack. Space for objects comes from the heap. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 8

Default Constructor n A default empty constructor is created automatically for you if you

Default Constructor n A default empty constructor is created automatically for you if you don’t have any constructor in your class: public classname (){ } n However, if you have defined some constructor(s) for the class, no default constructor will be created. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 9

Using Constructors n Download the following programs from the module website (“Resources” – “Lectures”)

Using Constructors n Download the following programs from the module website (“Resources” – “Lectures”) q q n Which of the following lines are valid when added into the main() method in Test. My. Class? a) b) c) d) + My. Class. java Test. My. Class. java My. Class © CS 1101 (AY 2009 -2010 Semester 1) a b c d = = new new My. Class(10, 3); My. Class(10, 1. 5); My. Class(); Week 7 - 10

Example of Overloaded Methods n Refer to the abs() method in Math class. public

Example of Overloaded Methods n Refer to the abs() method in Math class. public static int abs(int num) Returns the absolute value of num. public static double abs(double num) Returns the absolute value of num. n Hence, you may use abs() like this: int num = Math. abs(-40); double x = Math. abs(-3. 7); © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 11

So you think you know all about overloading? (1/2) n Given the following overloaded

So you think you know all about overloading? (1/2) n Given the following overloaded method public static void f(int a, int b) { System. out. println(a + b); } public static void f(double a, double b) { System. out. println(a – b); } n What are the outputs of the following codes? f(3, 6); f(3. 0, 6. 0); f(3, 6. 0); © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 12

So you think you know all about overloading? (2/2) n How about this public

So you think you know all about overloading? (2/2) n How about this public static void g(int a, double b) { System. out. println(a + b); } public static void g(double a, int b) { System. out. println(a – b); } n What is the output of the following code? g(3, 6); © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 13

Instance Methods and Class Methods (1/4) § There are two types of method. §

Instance Methods and Class Methods (1/4) § There are two types of method. § Instance method § Operates on an instance (object) of a class § Example: The length() method in String class String str = "Hello"; int len = str. length(); § Class method § Do not need to call it on an instance (object). § Examples: double ans = Math. abs(-4. 5); char ch = Character. to. Upper. Case('e'); Week 7 - 14

Instance Methods and Class Methods (2/4) § How do we know a method is

Instance Methods and Class Methods (2/4) § How do we know a method is an instance § method or a class method? Look at the API page § If you see the ‘static’ modifier, it is a class method. § If not, then it is an instance method. abs() is a class method. length() is an instance method. Week 7 - 15

Instance Methods and Class Methods (3/4) § Some classes provide only class methods §

Instance Methods and Class Methods (3/4) § Some classes provide only class methods § Example: Math § Some classes provide only instance methods § Example: Scanner § Some classes provide a mix § Example: String Week 7 - 16

Instance Methods and Class Methods (4/4) § When writing your own class, how do

Instance Methods and Class Methods (4/4) § When writing your own class, how do you decide § whether a method should be a class method or an instance method? Ask these questions: § “Is it necessary to create an instance in the application § program? ” “Is it necessary to call this method on individual instance (object) in order to access/retrieve some information pertaining only to that instance? ” § If answers are yes make it an instance method § If answers are no make it a class method § If answers are mixed/not clear use your judgement! Week 7 - 17

Calling a class method n You call a class method by preceding the call

Calling a class method n You call a class method by preceding the call with the name of the class that contains the method q n Examples: Math. abs(n), String. value. Of(1. 23) If the class method is called within the said class itself, it is optional to indicate the class q Example: Asterisks. V 2. java We may call print. Stars(2*i-1) or Asterisks. V 2. print. Stars(2*i-1) © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 18

Tracing codes n Download the following programs from the module website (“Resources” – “Lectures”)

Tracing codes n Download the following programs from the module website (“Resources” – “Lectures”) q q n n Without running the programs, trace the code and write down the output. Download the following programs from the module website (“Resources” – “Lectures”) q q n Vehicle. java Test. Vehicle. java Foo. java Test. Foo. java Without running the programs, trace the code and write down the output. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 19

Modular Programming Revisit (1/2) n Previous lecture: q q q n We compared Prime.

Modular Programming Revisit (1/2) n Previous lecture: q q q n We compared Prime. Test. Non. Modular. java with Prime. Test. java. We put the useful is. Prime(int) method in Prime class for reusability. We wrote an application Count. Primes. java to use the is. Prime(int) method in Prime. The is. Prime(int) method in Prime is a class method. Can we write it as an instance method? © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 20

Modular Programming Revisit (2/2) n n n Try it out! Call the new class

Modular Programming Revisit (2/2) n n n Try it out! Call the new class Prime. V 2 to avoid confusion. Call the application program Count. Primes. V 2, which is the counterpart of Count. Primes, to count the number of primes between two values, using the method in Prime. V 2. Let’s compare Prime. V 2 with Prime, and Count. Primes. V 2 with Count. Primes. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 21

private vs public n When do we write a private method? q q When

private vs public n When do we write a private method? q q When we don’t want or there is no need for any other class to use this method. It also arises when we do modularisation. public … XX(…) {. . . code-fragment-1 code-fragment-2. . . } public … XX(…) {. . . YY(…); ZZ(…); . . . } private … YY(…) { code-fragment-1 } private … ZZ(…) { code-fragment-2 } © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 22

Ball. V 3 n We will enhance our Ball class into version 3 to

Ball. V 3 n We will enhance our Ball class into version 3 to include the following features: q q n n Using ‘this’ in mutators Using overloaded constructors Creating a to. String() method Creating an equals() method Call this Ball. V 3. java Write an application program Test. Ball. V 3. java to create two ball objects, print their values, and compare them. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 23

Ball. V 3: to. String() method (1/2) n Given the following statements: System. out.

Ball. V 3: to. String() method (1/2) n Given the following statements: System. out. println("1 st ball: " + my. Ball 1); System. out. println("2 nd ball: " + my. Ball 2); n where my. Ball 1 and my. Ball 2 are two objects The output will look like this (actual output may differ slightly from below): 1 st ball: Ball. V 3@10 ef 90 c 2 nd ball: Ball. V 3@a 32 b n Hashcodes How do you get a custom-made output like this? 1 st ball: [blue, 1. 2, (8, 3)] 2 nd ball: [red, 3. 5, (-5, 12)] © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 24

Ball. V 3: to. String() method (2/2) n n n To make it work,

Ball. V 3: to. String() method (2/2) n n n To make it work, you need to write the to. String() method. The to. String() method returns a string, which is a string representation of the data in an object. Note that after to. String() method is defined in Ball. V 3, you may print my. Ball 1 object in any of these 2 ways: System. out. println(my. Ball 1); or System. out. println(my. Ball 1. to. String()); n Let’s add the to. String() method now. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 25

Ball. V 3: equals() method (1/2) n We create two objects my. Ball 1

Ball. V 3: equals() method (1/2) n We create two objects my. Ball 1 and my. Ball 2 with the same values. q q What is the truth value of (my. Ball 1 == my. Ball 2)? Why is it so? my. Ball 1 my. Ball 2 : Ball. V 3 colour red radius 2. 3 x. Coord 10 y. Coord 6 © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 26

Ball. V 3: equals() method (2/2) n We need to write an equals() method

Ball. V 3: equals() method (2/2) n We need to write an equals() method q q n Where should it be? In Ball. V 3 or Test. Ball. V 3? Why? Let’s write the equals() method now © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 27

Inherited methods and Overriding (1/3) n n The Ball. V 3 class, like every

Inherited methods and Overriding (1/3) n n The Ball. V 3 class, like every other Java class, is an extension (subclass) of class Object Class Object specifies some basic behaviors common to all objects Hence, these behaviors are inherited by all Java classes. Some inherited Object methods are q q n to. String() method equals() method However, the inherited methods usually don’t work (!) because they are not customised © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 28

Inherited methods and Overriding (2/3) n n + Hence, we often (almost always) need

Inherited methods and Overriding (2/3) n n + Hence, we often (almost always) need to customise these inherited methods This is called overriding We have written an overriding method to. String() for Ball. V 3 However, the equals() method we just wrote for Ball. V 3 is not an overriding method. Why? © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 29

Inherited methods and Overriding (3/3) n n Hence, to provide a truly overriding method

Inherited methods and Overriding (3/3) n n Hence, to provide a truly overriding method for equals(), this is what you need to write… (At the end of the day, it doesn’t matter which version you write. ) You will find overriding methods to. String() and equals() in many classes (see Point class for an example) We should write overriding methods to. String() and equals() for our own classes © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 30

Test. Ball. V 3: Modularisation (1/2) n Observe that there are duplicate codes in

Test. Ball. V 3: Modularisation (1/2) n Observe that there are duplicate codes in the input section of Test. Ball. V 3. java. It makes sense to write a method to read a ball’s data, create the object, and return it. System. out. print("Enter colour: "); input. Colour = scanner. next(); System. print("Enter radius: "); Identical code input. Radius = scanner. next. Double(); System. out. print("Enter centre’s x- and y-coordinates: "); input. XCoord = scanner. next. Int(); input. YCoord = scanner. next. Int(); Ball. V 3 my. Ball 1 = new Ball. V 3(input. Colour, input. Radius, input. XCoord, input. YCoord); System. out. print("Enter colour: "); input. Colour = scanner. next(); System. print("Enter radius: "); input. Radius = scanner. next. Double(); System. out. print("Enter centre’s x- and y-coordinates: "); input. XCoord = scanner. next. Int(); input. YCoord = scanner. next. Int(); Ball. V 3 my. Ball 2 = new Ball. V 3(input. Colour, input. Radius, input. XCoord, input. YCoord); © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 31

Test. Ball. V 3: Modularisation (2/2) n n Can you ‘modularise’ Test. Ball. V

Test. Ball. V 3: Modularisation (2/2) n n Can you ‘modularise’ Test. Ball. V 3. java so that you call a method read. Ball() each time you want to create a Ball. V 3 object? The follow code can then replace the previous: Ball. V 3 my. Ball 1 = read. Ball(scanner); Ball. V 3 my. Ball 2 = read. Ball(scanner); n n n We pass in the Scanner object scanner so that we create only one instance of Scanner in our program. Note that Course. Marker doesn’t work if we create multiple instances of Scanner. However, we are doing this not to avoid this Course. Marker problem, but it is not necessary to create multiple instances of Scanner, at least in this program. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 32

Point class (1/2) n n n We will introduce the Point class Textbook section

Point class (1/2) n n n We will introduce the Point class Textbook section 5. 6 Drawing Graphics Package: java. awt. * Field Summary x int The x coordinate. int y 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. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 33

Point class (2/2) Method Summary boolean Point double void equals(Object obj) Determines whether or

Point class (2/2) Method Summary boolean Point double void equals(Object obj) Determines whether or not two points are equal. get. Location() Returns the location of this point. get. X() Returns the X coordinate of the point in double precision. get. Y() Returns the Y coordinate of the point in double precision. move(int x, int y) Moves this point to the specified location in the (x, y) coordinate plane. void set. Location(double x, double y) Sets the location of this point to the specified double coordinates. set. Location(int x, int y) Changes the point to have the specified location. set. Location(Point p) Sets the location of the point to the specified location. String to. String() Returns a string representation of this point and its location in the (x, y) coordinate space. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 34

Using Point class (1/6) n Test. Point. java import java. awt. *; class Test.

Using Point class (1/6) n Test. Point. java import java. awt. *; class Test. Point { public static void f(Point v) { v = new Point(0, 0); } public static void g(Point v) { v. set. Location(0, 0); } } + public static void main(String[] args) { Point p = new Point(10, 10); System. out. println(p); f(p); System. out. println(p); g(p); System. out. println(p); } © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 35

Using Point class (2/6) public static void main(String[] args) { Point p = new

Using Point class (2/6) public static void main(String[] args) { Point p = new Point(10, 10); public static System. out. println(p); void f(Point v) { v = new Point(0, 0); } f(p); main() p : Point x: 10 y: 10 f() v Output: java. awt. Point[x=10, y=10] © CS 1101 (AY 2009 -2010 Semester 1) Method main()’s variable p and method f()’s formal parameter v have the same value, which is a reference to an object representing location (10, 10). Week 7 - 36

Using Point class (3/6) public static void main(String[] args) { Point p = new

Using Point class (3/6) public static void main(String[] args) { Point p = new Point(10, 10); public static System. out. println(p); void f(Point v) { v = new Point(0, 0); } f(p); main() p : Point y: 10 x: 10 f() v Output: java. awt. Point[x=10, y=10] © CS 1101 (AY 2009 -2010 Semester 1) : Point x: 0 y: 0 Week 7 - 37

Using Point class (4/6) public static void main(String[] args) { Point p = new

Using Point class (4/6) public static void main(String[] args) { Point p = new Point(10, 10); System. out. println(p); f(p); System. out. println(p); main() p : Point y: 10 x: 10 f() v Output: java. awt. Point[x=10, y=10] : Point x: 0 y: 0 java. awt. Point[x=10, y=10] © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 38

Using Point class (5/6) public static void main(String[] args) { Point p = new

Using Point class (5/6) public static void main(String[] args) { Point p = new Point(10, 10); public static System. out. println(p); void g(Point v) { v. set. Location(0, 0); } f(p); System. out. println(p); g(p); main() p : Point x: 10 0 y: 10 0 g() v Output: java. awt. Point[x=10, y=10] © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 39

Using Point class (6/6) public static void main(String[] args) { Point p = new

Using Point class (6/6) public static void main(String[] args) { Point p = new Point(10, 10); System. out. println(p); f(p); System. out. println(p); g(p); System. out. println(p); main() p : Point x: 10 0 y: 10 0 Output: java. awt. Point[x=10, y=10] java. awt. Point[x=0, y=0] © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 40

Other Point related classes n Check them out q q Point 2 D. Double

Other Point related classes n Check them out q q Point 2 D. Double Point 2 D. Float © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 41

Common mistake n Common mistake with using objects q n Note that declaring an

Common mistake n Common mistake with using objects q n Note that declaring an object creating an object q n Accessing an object when it does not exist Only a new statement creates an object (exception: String) The following is wrong: Point pt; System. out. println(pt. get. X()); pt. set. Location(10, 20); © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 42

Ball. V 4: Using Point for centre n n n Currently, we use x.

Ball. V 4: Using Point for centre n n n Currently, we use x. Coord and y. Coord to represent the centre of a ball object. Now, enhance your Ball class into version 4 by replacing x. Coord and y. Coord with Point for the centre. Call this Ball. V 4. java Write an application program Test. Ball. V 4. java to create two ball objects, print their values, and compare them. Please bring along your programs to your discussion session this Friday. Your DL will check your programs and discuss them. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 43

Summary for Today n n Writing modular programs revisit More about OOP q q

Summary for Today n n Writing modular programs revisit More about OOP q q q n Instance method vs class method Using private vs public method Using ‘this’ Overloading methods Overriding methods The Point class © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 44

Announcements/Things-to-do (1/2) n Complete the following q n To prepare for next lecture q

Announcements/Things-to-do (1/2) n Complete the following q n To prepare for next lecture q n Ball. V 4. java and Test. Ball. V 4. java Read Chapters 9 – 10 and their Power. Point files before you come for lecture. To prepare for this Friday’s discussion session: q Download “week 7_discussion_qns. pdf” from module website, “CA – Discussion”. q Do the questions before you attend your discussion session. © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 45

Announcements/Things-to-do (2/2) n Take-home Lab #4 q n This lab will take you more

Announcements/Things-to-do (2/2) n Take-home Lab #4 q n This lab will take you more time than the previous labs. Please start working on it early. You may clarify your doubts at this Friday’s discussion session or at the next lecture. Mid-term test q q This Saturday, 3 October 2009 Refer to module website (“CA” – “Termtests”) for details © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 46

End of File © CS 1101 (AY 2009 -2010 Semester 1) Week 7 -

End of File © CS 1101 (AY 2009 -2010 Semester 1) Week 7 - 47