comp 110 introduction to programming mr. joshua stough october 8, 2007
Post on 20-Dec-2015
217 views
TRANSCRIPT
COMP 110Introduction to Programming
Mr. Joshua StoughOctober 8, 2007
Announcements
• Recitation this week:– more practice writing methods
• Reminder: – Program 3 due Wednesday– Homework 4 due Wednesday
Review
public static int countCharInWord (char ch, String word)
methodnamereturn
type
formal parameter list
The parameter list specifies the typeand name of each parameter
The name of a parameter in the methoddeclaration is called a formal argument
A method declaration begins with a method header
visibilitymodifiers
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 beconsistent 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)
ReviewEach 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
• 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 ScopeExample
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()
}
}
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
Overloading Methods
public static double tryMe (int x){ return x + .375;}
Version 1
public static double tryMe (int x, float y){ return x*y;}
Version 2
Invocationresult = tryMe (25, 4.32)
Overloaded Methodsprintln 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);
Class/Method Style
• Above each class header– box-like comment describing the
member variables, private methods, and public methods
• Above each method header– box-like comment describing the
purpose of the method, including any parameters it takes and any data returned
Style Example/********************************************************** * Rectangle * * Member Variables: * int length - represents the length of the rectangle * int width - represents the width of the rectangle * Private Methods: none * Public Methods: * ... * int computeArea() - returns area as an integer *********************************************************/public class Rectangle {
// variables and other methods omitted/****************************************************
* computeArea * * Returns the area of the rectangle (width * length)
***************************************************/public int computeArea(){
// method body omitted}
}
QuestionWriting 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
SolutionWriting Methods
{int sum = 0;
for (int num = 1; num<=100; num++) {sum += num;
}
return sum;}
public static int sum100 ()
QuestionWriting 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.
SolutionWriting Methods
{if (num1 > num2) {
return true;}
return false;}
public static boolean larger (double num1, double num2)
QuestionWriting 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)
QuestionOverloading 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 namethat 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
• 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 name
data members
methods
Rectangle.javaSo Far
public class Rectangle{
// data membersprivate 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 theRectangle class can directly access the datamembers
Implementing Rectangle...
{length = l;
}
public void setLength (int l)
public void setWidth (int w){
width = w;}
Remember: accordingto scope rules, themethods in Rectanglecan directly accesswidth and length.
Implementing Rectangle...public int getLength(){
return length;}
{return width;
}
public int getWidth()
Implementing Rectangle...public int computePerimeter(){
return (width*2 + length*2);}
{return (width * length);
}
public int computeArea()
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
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
reservedword
constructormethod
use emptyparentheseswhen noparameterto method
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
Constructor
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
• Typical Order in the Java Source File:– data members– constructor(s)– other methods
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
Rectangle r2 = new Rectangle (20, 30);
3800
4500
r1
r2
3800
4500
5 10
20 30
Rectangle r1 = new Rectangle (5, 10);
r2500
2500
2 3
Using the Rectangle Class• Create an object:
Rectangle r;r = new Rectangle(2, 3);ORRectangle r = new Rectangle(2, 3);
• Use the object and the dot operator to access methods:r.setLength(5);r.setWidth(10);
r
2 3
25002500
5 10
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 ModifiersGuidelines• 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
• 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
• 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.
computeArea();
computeAreaprint
Method Control FlowThe called method can be within the same class as the caller, in which case only the method name is needed
computeArea
computeArea();
obj.print();
main
Method Control FlowThe called method can be part of another class or object
RectangleTester.javaRectangle 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
Thought Exercise
• 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 110
• More writing classes
• Homework 4 / Program 3 due Wednesday
• Reading: Ch 7, review