lecture17

Uploaded from authorPOINTLite
Views:
 
Category: Entertainment
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

COMP 14 - 02 : 

COMP 14 - 02 Andrew Leaver-Fay October 31, 2004

Announcements: 

Announcements Program 2 Due Wednesday, November 2 Office hours today Office Hours Wednesday: from 5:30 to 6:30 (Sitterson, Room 042)

Review: 

Review public static int countCharInWord (char ch, String word) method name return type formal parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument A method declaration begins with a method header visibility modifiers

Review: 

Review The method header is followed by the method body { int count = 0; for (int i = 0; i<word.length(); i++) { if (word.charAt(i) == ch) { count++; } } return count; } The return expression must be consistent with the return type ch and word are local data They are created each time the method is called, and are destroyed when it finishes executing public static int countCharInWord (char ch, String word)

Review: Calling Methods: 

Review: Calling Methods Invoke, or Call a method by naming it public class Lecture18TestClass { public static void main( String[] args ) { System.out.println( countCharsInWord( ‘e’, “Halloween” ) ); } public static int countCharInWord(char ch, String str) { //… } }

Review: 

Review Each time a method is called, the actual parameters in the call are copied into the formal parameters int num = countCharInWord ('e', "Heels"); { int count = 0; for (int i = 0; i<word.length(); i++) { if (word.charAt(i) == ch) { count++; } } return count; } public static int countCharInWord (char ch, String word)

Data Scope: 

Data Scope The scope of data is the area in a program in which that data can be used (referenced) Data declared at the class level can be used by all methods in that class Data declared within a method can be used only in that method Also called local data Key to determining scope is to look for blocks of code (surrounded by { }) Variables declared inside { } cannot be used outside

Data Scope Example: 

Data Scope Example public class Rectangle { // variables declared here are class-level // available in all methods in Rectangle class public int computeArea() { // variables declared here are method-level // only available in computeArea() } public void print() { // variables declared here are method-level // only available in print() } }

Review: Overloading Methods: 

Review: Overloading Methods Overloading - the process of using the same method name for multiple methods The signature of each overloaded method must be unique Number of parameters Type of the parameters not the return type of the method, though The compiler determines which version of the method is being invoked by analyzing the parameters

Review: Overloading Methods: 

Review: Overloading Methods Invocation result = tryMe (25, 4.32)

Overloaded Methods println Example: 

Overloaded Methods println Example The println method is overloaded: println (String s) println (int i) println (double d) and so on... The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total);

Question Writing Methods: 

Question Writing Methods Write a method called sum100 that returns the sum of the integers from 1 to 100, inclusive. Steps: Write the method header public static returnType methodName (formal parameters) Think about the problem and develop an algorithm for solving the problem Write the method body

Solution Writing Methods: 

Solution Writing Methods { int sum = 0; for (int num = 1; num<=100; num++) { sum += num; } return sum; } public static int sum100 ()

Question Writing Methods: 

Question Writing Methods Write a method called larger that accepts two double parameters and returns true if the first parameter is greater than the second and false otherwise.

Solution Writing Methods: 

Solution Writing Methods { if (num1 > num2) { return true; } return false; } public static boolean larger (double num1,double num2)

Question Writing Methods: 

Question Writing Methods Write a method called average that accepts two integer parameters and returns their average as a double. { int sum = num1 + num2; return (sum / 2.0); } public static double average (int num1, int num2)

Question Overloading Methods: 

Question Overloading Methods Overload the average method such that if three integers are provided as parameters, the method returns the average of all three. Write another method with the same name that has a different parameter list. { int sum = num1 + num2 + num3; return (sum / 3.0); } public static double average (int num1, int num2, int num3)

Objects and Classes: 

Objects and Classes An object's data type is a class The class contains the data types that make up the object and what methods can operate on the object Properties (data members, or member variables) Actions (methods)

class Rectangle Data Members and Operations: 

class Rectangle Data Members and Operations class name data members methods

Rectangle.java So Far: 

Rectangle.java So Far public class Rectangle { // data members private int length_; private int width_; // methods // setLength // setWidth // getLength // getWidth // computePerimeter // computeArea // print } //public void setLength (int l) //public void setWidth (int w) //public int getLength() //public int getWidth() //public int computePerimeter() //public int computeArea() //public void print() only methods from the Rectangle class can directly access the data members

Implementing Rectangle...: 

Implementing Rectangle... { length_ = l; } public void setLength (int l) public void setWidth (int w) { width_ = w; } Remember: according to scope rules, the methods in Rectangle can directly access width and length.

Implementing Rectangle...: 

Implementing Rectangle... public int getLength() { return length_; } { return width_; } public int getWidth()

Implementing Rectangle...: 

Implementing Rectangle... public int computePerimeter() { return (width_*2 + length_*2); } { return (width_ * length_); } public int computeArea()

Implementing Rectangle...: 

Implementing Rectangle... public void print() { System.out.print ("The perimeter of the " + length_ + "x" + width_); System.out.print (" rectangle is " + computePerimeter()); System.out.println (" and the area is " + computeArea()); }

Creating an Object: 

Creating an Object Before we can access the members (variables and methods) of a class, we have to instantiate, or create, an object Rectangle r = new Rectangle(); class name variable name reserved word constructor method use empty parentheses when no parameter to method

Constructors: 

Constructors A constructor is a special method that is used to initialize a newly created object When writing a constructor, remember that: it has the same name as the class it does not return a value it has no return type, not even void it typically sets the initial values of instance variables The programmer does not have to, but usually should, define a constructor for a class

Constructors: 

Constructors public Rectangle (int l, int w) { length = l; width = w; } public class Rectangle { private int length; private int width; Rectangle r2 = new Rectangle (5, 10); public Rectangle () { length = 0; width = 0; }

Rectangle.java: 

Rectangle.java Typical Order in the Java Source File: data members constructor(s) other methods

Instance Data: 

Instance Data The length_ and width_ variables in the Rectangle class are called instance data Each instance (object) of the Rectangle class have its own width_ and length_ variables Every time a Rectangle object is created, new width_ and length_ variables are created as well The objects of a class share the method definitions, but each has its own data space The only way two objects can have different states -- two different memory locations

Rectangles in Memory: 

Rectangles in Memory Rectangle r2 = new Rectangle (20, 30); 3800 4500 r1 r2 3800 4500 5 10 20 30 Rectangle r1 = new Rectangle (5, 10);

Using the Rectangle Class: 

Create an object: Rectangle r; r = new Rectangle(2, 3); OR Rectangle r = new Rectangle(2, 3); Use the object and the dot operator to access methods: r.setLength(5); r.setWidth(10); r 2500 2500 2 3 Using the Rectangle Class r 2 3 2500 2500 5 10

Visibility Modifiers: 

Visibility Modifiers public visibility Can be accessed from anywhere private visibility Can only be accessed from inside the class (inside the same Java source file) default visibility Members declared without a visibility modifier Can be accessed by any class in the same package public class Rectangle { private int length; private int width; } public Rectangle () { length = 0; width = 0; } ...

Visibility Modifiers Guidelines: 

Visibility Modifiers Guidelines Usually declare data members with private visibility Declare methods that clients (other classes) are supposed to call with public visibility Service methods Declare methods that only other methods in the class are supposed to call with private visibility Support methods

UML Diagram: 

UML Diagram Top box: name of class Middle box: data members and their data types Bottom box: member methods’ names, parameter list, return type of method + means public - means private Rectangle -length: int -width: int +Rectangle() +Rectangle(int, int) +setLength(int): void +setWidth(int): void +getLength(): int +getWidth(): int +computePerimeter(): int +computeArea(): int +print(): void

Driver Programs: 

Driver Programs Classes containing the main method that we use to test our classes It's very useful to first write your classes and write a driver program to test them out before you try to complete all of the requirements of the assignment

Method Control Flow: 

computeArea(); computeArea print Method Control Flow The called method can be within the same class as the caller, in which case only the method name is needed

Method Control Flow: 

Method Control Flow The called method can be part of another class or object

RectangleTester.java: 

RectangleTester.java Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle (20, 30); r1.setWidth(5); r1.setLength(10); r1.print(); r2.print(); Must be looking at class with main method to run the program Exception in thread "main" java.lang.NoSuchMethodError: main Don't forget to re-compile files after making changes

The Modifier static: 

The Modifier static In the method heading, specifies that the method can be invoked by using the name of the class No object has to be created in order to use the method Can't call a non-static method from a static method Can't access non-static variables from a static method If used to declare data member, data member invoked by using the class name No object has to be created in order to use the variables

static Variables: 

static Variables Shared among all objects of the class Memory created for static variables when class is loaded Memory created for instance variables (non-static) when an object is instantiated (using new) If one object changes the value of the static variable, it is changed for all objects of that class Only one copy of the static variable, so all instances that look at the static variable look at the same copy

static Methods: 

static Methods int num = Integer.parseInt(“45”); parseInt is a static method inside the Integer class int num = Integer.intValue(); intValue is NOT a static method inside the Integer class Integer n = new Integer(10); int num = n.intValue(); class method

Illustrate Class (pg. 421): 

Illustrate Class (pg. 421) public class Illustrate { private int x; public static int y; private static int count; public Illustrate() { x = 0; } public Illustrate (int a) { x = a; } public static void incrementCount() { count++; } } Illustrate obj1 = new Illustrate(3); Illustrate.incrementCount(); 1 1 Illustrate obj2 = new Illustrate(5); Illustrate.y++;

Practice: 

Practice Write a method for the Rectangle class called printBox that will print the rectangle as a box made of % example: length_ = 3, width_ = 5 %%%%% % % %%%%%

Next Time in COMP 14: 

Next Time in COMP 14 More Arrays Program 2 due Wednesday by 11:59