CS1101: Programming Methodology

Slides:



Advertisements
Similar presentations
The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
Advertisements

Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
CS102--Object Oriented Programming Discussion 2: (programming strategy in java) – Two types of tasks – The use of arrays Copyright © 2008 Xiaoyan Li.
Chapter 41 Defining Classes and Methods Chapter 4.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
1 Memory Model of A Program, Methods Overview l Closer Look at Methods l Memory Model of JVM »Method Area »Heap »Stack l Preview: Parameter Passing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
CS1101: Programming Methodology
Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing.
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.
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology
1 Programming with methods and classes. 2 Methods  Instance (or member) method Operates on a object (i.e., and instance of the class) String s = new.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Procedural programming in Java Methods, parameters and return values.
CS1101: Programming Methodology
CS1101: Programming Methodology Aaron Tan.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS1101: Programming Methodology Aaron Tan.
Session 7 Methods Strings Constructors this Inheritance.
CS1101: Programming Methodology
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
2.3 The Java API Documentation. What follows are the contents of the Java Application Programming Interface (API) Documentation for the system supplied.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
© 2007 Lawrenceville Press Slide 1 Chapter 8 Objects  A variable of a data type that is a class. Also called an instance of a class.  Stores data  Can.
Introduction to Methods Shirley Moore CS 1401 Spring 2013 cs1401spring2013.pbworks.com April 1, 2013.
Programming with methods and classes. Methods  Instance method Operates on a object (i.e., and instance of the class) String s = new String("Help every.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Programming with methods and classes Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
CS1101: Programming Methodology
CS1101: Programming Methodology
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Chapter 7: Programming with methods and classes..
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Defining Your Own Classes II
Chapter 7 User-Defined Methods.
Static data members Constructors and Destructors
Chapter 3 Inheritance © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Programming with methods and classes
Programming with methods and classes
Chapter 4 Writing Classes.
Building Java Programs
Building Java Programs
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Classes, Objects and Methods
Building Java Programs
Building Java Programs
Review for Midterm 3.
Presentation transcript:

CS1101: Programming Methodology

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 © CS1101 (AY Semester 1)Week7 - 2

Welcome Back!  ARE YOU ENERGISED? © CS1101 (AY Semester 1)Week7 - 3

MasterMind Have you completed your program? Show it to us! © CS1101 (AY Semester 1)Week7 - 4

Chapter 7 Let’ go over Thomas Wu’s slides now… © CS1101 (AY Semester 1)Week7 - 5

Method Invocation (1/3) Given the following public void setRadius(double r) { … } public static void main(String[] args) { … ball.setRadius(s); } r is called the formal parameter s is the actual parameter Pass-by-value: The value of s is copied into r. © CS1101 (AY Semester 1)Week7 - 6

Method Invocation (2/3) Actual parameters provide information that is otherwise unavailable to a method When a method is invoked  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 © CS1101 (AY Semester 1)Week7 - 7

Method Invocation (3/3) Java divides the memory allocated to a program into two portions: stack and heap.  Activation records are maintained in the stack.  Space for objects comes from the heap. © CS1101 (AY Semester 1)Week7 - 8

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

Using Constructors Download the following programs from the module website (“Resources” – “Lectures”)  MyClass.java  TestMyClass.java Which of the following lines are valid when added into the main() method in TestMyClass? a) MyClass a = new MyClass(10, 3); b) MyClass b = new MyClass(10); c) MyClass c = new MyClass(10, 1.5); d) MyClass d = new MyClass(); © CS1101 (AY Semester 1)Week

Example of Overloaded Methods Refer to the abs() method in Math class.Math public static int abs(int num) Returns the absolute value of num. public static double abs(double num) Returns the absolute value of num. Hence, you may use abs() like this: int num = Math.abs(-40); double x = Math.abs(-3.7); © CS1101 (AY Semester 1)Week7 - 11

So you think you know all about overloading? (1/2) 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); } What are the outputs of the following codes? f(3, 6); f(3.0, 6.0); f(3, 6.0); © CS1101 (AY Semester 1)Week7 - 12

So you think you know all about overloading? (2/2) 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); } What is the output of the following code? g(3, 6); © CS1101 (AY Semester 1)Week7 - 13

Week 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.toUpperCase('e');

Week 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 Instance Methods and Class Methods (3/4)  Some classes provide only class methods  Example: MathMath  Some classes provide only instance methods  Example: ScannerScanner  Some classes provide a mix  Example: StringString

Week 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!

Calling a class method You call a class method by preceding the call with the name of the class that contains the method  Examples: Math.abs(n), String.valueOf(1.23) If the class method is called within the said class itself, it is optional to indicate the class  Example: AsterisksV2.java We may call printStars(2*i-1) or AsterisksV2.printStars(2*i-1) © CS1101 (AY Semester 1)Week7 - 18

Tracing codes Download the following programs from the module website (“Resources” – “Lectures”)  Vehicle.java  TestVehicle.java Without running the programs, trace the code and write down the output. Download the following programs from the module website (“Resources” – “Lectures”)  Foo.java  TestFoo.java Without running the programs, trace the code and write down the output. © CS1101 (AY Semester 1)Week7 - 19

Modular Programming Revisit (1/2) Previous lecture:  We compared PrimeTestNonModular.java with PrimeTest.java.  We put the useful isPrime(int) method in Prime class for reusability.  We wrote an application CountPrimes.java to use the isPrime(int) method in Prime. The isPrime(int) method in Prime is a class method. Can we write it as an instance method? © CS1101 (AY Semester 1)Week7 - 20

Modular Programming Revisit (2/2) Try it out! Call the new class PrimeV2 to avoid confusion. Call the application program CountPrimesV2, which is the counterpart of CountPrimes, to count the number of primes between two values, using the method in PrimeV2. Let’s compare PrimeV2 with Prime, and CountPrimesV2 with CountPrimes. © CS1101 (AY Semester 1)Week7 - 21

private vs public When do we write a private method?  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. © CS1101 (AY Semester 1)Week public … XX(…) {... code-fragment-1 code-fragment-2... } public … XX(…) {... YY(…); ZZ(…);... } private … YY(…) { code-fragment-1 } private … ZZ(…) { code-fragment-2 }

BallV3 We will enhance our Ball class into version 3 to include the following features:  Using ‘this’ in mutators  Using overloaded constructors  Creating a toString() method  Creating an equals() method Call this BallV3.java Write an application program TestBallV3.java to create two ball objects, print their values, and compare them. © CS1101 (AY Semester 1)Week7 - 23

BallV3: toString() method (1/2) Given the following statements: System.out.println("1st ball: " + myBall1); System.out.println("2nd ball: " + myBall2); where myBall1 and myBall2 are two objects The output will look like this (actual output may differ slightly from below): 1st ball: 2nd ball: © CS1101 (AY Semester 1)Week Hashcodes How do you get a custom-made output like this? 1st ball: [blue, 1.2, (8, 3)] 2nd ball: [red, 3.5, (-5, 12)]

BallV3: toString() method (2/2) To make it work, you need to write the toString() method. The toString() method returns a string, which is a string representation of the data in an object. Note that after toString() method is defined in BallV3, you may print myBall1 object in any of these 2 ways: System.out.println(myBall1); or System.out.println(myBall1.toString()); Let’s add the toString() method now. © CS1101 (AY Semester 1)Week7 - 25

BallV3: equals() method (1/2) We create two objects myBall1 and myBall2 with the same values.  What is the truth value of (myBall1 == myBall2)?  Why is it so? © CS1101 (AY Semester 1)Week myBall1 :BallV3 colour radius xCoord yCoord red myBall2 :BallV3 colour radius xCoord yCoord red

BallV3: equals() method (2/2) We need to write an equals() method  Where should it be? In BallV3 or TestBallV3?  Why? Let’s write the equals() method now © CS1101 (AY Semester 1)Week7 - 27

Inherited methods and Overriding (1/3) The BallV3 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  toString() method  equals() method However, the inherited methods usually don’t work (!) because they are not customised © CS1101 (AY Semester 1)Week7 - 28

Inherited methods and Overriding (2/3) Hence, we often (almost always) need to customise these inherited methods This is called overriding We have written an overriding method toString() for BallV3 However, the equals() method we just wrote for BallV3 is not an overriding method. Why? © CS1101 (AY Semester 1)Week

Inherited methods and Overriding (3/3) 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 toString() and equals() in many classes (see Point class for an example) We should write overriding methods toString() and equals() for our own classes © CS1101 (AY Semester 1)Week7 - 30

TestBallV3: Modularisation (1/2) Observe that there are duplicate codes in the input section of TestBallV3.java. It makes sense to write a method to read a ball’s data, create the object, and return it. © CS1101 (AY Semester 1)Week System.out.print("Enter colour: "); inputColour = scanner.next(); System.print("Enter radius: "); inputRadius = scanner.nextDouble(); System.out.print("Enter centre’s x- and y-coordinates: "); inputXCoord = scanner.nextInt(); inputYCoord = scanner.nextInt(); BallV3 myBall1 = new BallV3(inputColour, inputRadius, inputXCoord, inputYCoord); System.out.print("Enter colour: "); inputColour = scanner.next(); System.print("Enter radius: "); inputRadius = scanner.nextDouble(); System.out.print("Enter centre’s x- and y-coordinates: "); inputXCoord = scanner.nextInt(); inputYCoord = scanner.nextInt(); BallV3 myBall2 = new BallV3(inputColour, inputRadius, inputXCoord, inputYCoord); Identical code

TestBallV3: Modularisation (2/2) Can you ‘modularise’ TestBallV3.java so that you call a method readBall() each time you want to create a BallV3 object? The follow code can then replace the previous: © CS1101 (AY Semester 1)Week BallV3 myBall1 = readBall(scanner); BallV3 myBall2 = readBall(scanner); We pass in the Scanner object scanner so that we create only one instance of Scanner in our program. Note that CourseMarker doesn’t work if we create multiple instances of Scanner. However, we are doing this not to avoid this CourseMarker problem, but it is not necessary to create multiple instances of Scanner, at least in this program.

Point class (1/2) We will introduce the Point classPoint Textbook section 5.6 Drawing Graphics Package: java.awt.* © CS1101 (AY Semester 1)Week Field Summary int x x The x coordinate. int y y The y coordinate. Constructor Summary PointPoint() Constructs and initializes a point at the origin (0, 0) of the coordinate space. PointPoint(int x, int y) Constructs and initializes a point at the specified ( x, y) location in the coordinate space. PointPoint(Point p) Constructs and initializes a point with the same location as the specified Point object.Point

Point class (2/2) © CS1101 (AY Semester 1)Week Method Summary boolea n equalsequals(Object obj) Determines whether or not two points are equal.Object Point getLocationgetLocation() Returns the location of this point. doubl e getXgetX() Returns the X coordinate of the point in double precision. doubl e getYgetY() Returns the Y coordinate of the point in double precision. void movemove(int x, int y) Moves this point to the specified location in the ( x, y) coordinate plane. void setLocationsetLocation(double x, double y) Sets the location of this point to the specified double coordinates. void setLocationsetLocation(int x, int y) Changes the point to have the specified location. void setLocationsetLocation(Point p) Sets the location of the point to the specified location.Point String toStringtoString() Returns a string representation of this point and its location in the ( x, y) coordinate space.

Using Point class (1/6) © CS1101 (AY Semester 1)Week import java.awt.*; class TestPoint { public static void f(Point v) { v = new Point(0, 0); } public static void g(Point v) { v.setLocation(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); } TestPoint.java +

Using Point class (2/6) © CS1101 (AY Semester 1)Week public static void main(String[] args) { Point p = new Point(10, 10); System.out.println(p); f(p); main() p :Point y: 10 x: 10 java.awt.Point[x=10,y=10] public static void f(Point v) { v = new Point(0, 0); } f() v 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). Output:

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

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

Using Point class (5/6) © CS1101 (AY Semester 1)Week public static void main(String[] args) { Point p = new Point(10, 10); System.out.println(p); f(p); System.out.println(p); g(p); java.awt.Point[x=10,y=10] Output: java.awt.Point[x=10,y=10] main() p :Point y: 10 x: 10 public static void g(Point v) { v.setLocation(0, 0); } v g() 0 0

Using Point class (6/6) © CS1101 (AY Semester 1)Week 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); java.awt.Point[x=10,y=10] Output: java.awt.Point[x=10,y=10] main() p :Point y: 10 x: java.awt.Point[x=0,y=0]

Other Point related classes Check them out  Point2D.Double Point2D.Double  Point2D.Float Point2D.Float © CS1101 (AY Semester 1)Week7 - 41

Common mistake Common mistake with using objects  Accessing an object when it does not exist Note that declaring an object  creating an object  Only a new statement creates an object (exception: String) The following is wrong: © CS1101 (AY Semester 1)Week Point pt; System.out.println(pt.getX()); pt.setLocation(10, 20);

BallV4: Using Point for centre Currently, we use xCoord and yCoord to represent the centre of a ball object. Now, enhance your Ball class into version 4 by replacing xCoord and yCoord with Point for the centre. Call this BallV4.java Write an application program TestBallV4.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. © CS1101 (AY Semester 1)Week7 - 43

Summary for Today Writing modular programs revisit More about OOP  Instance method vs class method  Using private vs public method  Using ‘this’  Overloading methods  Overriding methods The Point class © CS1101 (AY Semester 1)Week7 - 44

Announcements/Things-to-do (1/2) Complete the following  BallV4.java and TestBallV4.java To prepare for next lecture  Read Chapters 9 – 10 and their PowerPoint files before you come for lecture. To prepare for this Friday’s discussion session:  Download “week7_discussion_qns.pdf” from module website, “CA – Discussion”.  Do the questions before you attend your discussion session. © CS1101 (AY Semester 1)Week7 - 45

Announcements/Things-to-do (2/2) Take-home Lab #4  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  This Saturday, 3 October 2009  Refer to module website (“CA” – “Termtests”) for details © CS1101 (AY Semester 1)Week7 - 46

End of File © CS1101 (AY Semester 1)Week7 - 47