Download Lecture 06: Methods: A Deeper Look

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Spring 2009
Programming Fundamentals I
Java Programming
Lecture No. 6
XuanTung Hoang
[email protected]
Methods: A Deeper Look
1.
2.
3.
4.
5.
6.
7.
Motivation of methods
Static methods and static fields of a class
Summary of calling methods
Method call mechanism: Stack and Activation Records
Type Casting and Argument Promotion
Scope of Declarations
Method Overloading
Motivation of Methods (2)

We have mentioned about methods in Lecture 3



Methods are members of a class
Methods capture capability of an class object (instance)
Methods are useful for:


Manageability: a complex task can be managed more easily if we
can divide it into smaller tasks (divide-and-conquer)
Reusability: We write a method once and reuse it by calling it.
(E.g.: method nextInt() of class Scanner)
XuanTung Hoang
3
What we knew about methods
0,1 or more
modifiers
0 or 1 returned
type
Method name
0,1 or more
arguments
public class GradeBook {
// method to retrieve the course name
public String getCourseName(
Method body
) {
return courseName;
}
} // end class GradeBook
Method signature
return
statement


void return type is different from no return type
Agreement between return type and return expression
XuanTung Hoang
4
What we knew about methods
“Object can perform actions only if exists”


“Normal” method can be called only if object exists.
GradeBook.java
1
public class GradeBook {
2
// display a welcome message to the GradeBook user
3
public void displayMessage() {
4
5
6
System.out.println("Welcome to the Grade Book!");
} // end method display message
} // end class GradeBook
GradeBook myGradeBook;
myGradeBook.displayMessage();
Normal methods are associated
with a specific object
XuanTung Hoang
Error! Since an instance
of Gradebook class is
not created
5
Static methods and fields

There are special cases
Calling a method
without creating an
object!!
double v = 19382.23;
double result = Math.sqrt(v);
System.out.printf("Square root of %f is %f", v, result);
static methods can be called without creating object
XuanTung Hoang
6
Static methods and fields


Static methods and fields (instance variables) are associated with a
class, not a specific object
Calling a static method via class name
 ClassName.methodName(arguments)




E.g.: Math.sqrt(0.09);
“Field” means “instance variable”
static field (or static instance variable) is also called “class variables”
Can also be accessed via class name

E.g.: System.out.printf(“%f”, Math.PI)
XuanTung Hoang
7
Class Math
XuanTung Hoang
All methods and
constants defined in
class Math are static.
We can use them
immediately (without
creating Math objects)
8
See more in Java API Manual …
XuanTung Hoang
9
Why main method should be static?

When a java program is started, there is no object exists!!!
Declaring main method as static allows the method to be
invoked.
GradeBookTest.java
1
2
3
4
5
6
7
8
9
10
11
// Create GradeBook object and call its displayMessage method
public class GradeBookTest {
// Program entry
public
static
void main(String args[]) {
String nameOfCourse = "ICE0124";
// create GradeBook object and assign it to myGradeBook
GradeBook myGradeBook= new GradeBook();
// Call displayMessage method of myGradeBook
myGradeBook.displayMessage(nameOfCourse);
}
}
XuanTung Hoang
10
main method

main method can be placed in any class
GradeBook.java
public class GradeBook {
1
2
// display a welcome message to the GradeBook user
public void displayMessage(String courseName) {
3
4
System.out.printf("Welcome to the Grade Book for %s!\n",courseName);
5
} // end method display message
6
} // end class GradeBook
Copy the
code to
here
GradeBookTest.java
1
2
3
4
5
6
7
8
9
10
11
// Create GradeBook object and call its displayMessage method
public class GradeBookTest {
// Program entry
public static void main(String args[]) {
String nameOfCourse = "ICE0124";
// create GradeBook object and assign it to myGradeBook
GradeBook myGradeBook= new GradeBook();
// Call displayMessage method of myGradeBook
myGradeBook.displayMessage(nameOfCourse);
}
}
XuanTung Hoang
11
Calling methods

Call a method using object reference

objectReference.methodName( … )

Example:
GradeBook myGradeBook = new GradeBook(“ICE0124”);
myGradeBook.displayMessage();


Apply to “normal” methods (non-static methods)
Call a method using class name

ClassName.methodName( … )



Example: Math.sqrt(0.09);
Apply to static methods only
Call a method in the same class
XuanTung Hoang
12
Calling methods

Call a method in the same class
public class MaximumFinder {
public double maximum( double x, double y, double z) {
// code that finds the maximum value among
Don’t need to provide object reference
// x, y , and z
or class name
}
public void determineMax() Or
{ using this to refer to the current
Scanner input = new Scanner(
object System.in );
double number1, number2, number3;
number1 = input.nextDouble();
number2 = input.nextDouble();
number3 = input.nextDouble();
double result = maximum( number1, number2, number3 );
double result = this.maximum( number1, number2, number3);
}
}
XuanTung Hoang
13
Notices about static methods
public class MaximumFinder {
public double maximum( double x, double y, double z) {
// code that finds the maximum value among
// x, y , and z
Is it ok ?
}
public
static
void determineMax() {
Scanner input = new Scanner( System.in ); NO! the class cannot
double number1, number2, number3;
be compiled
number1 = input.nextDouble();
Why ?
number2 = input.nextDouble();
number3 = input.nextDouble();
double result = maximum( number1, number2, number3 );
}
}
static methods CANNOT directly call non-static methods of the same
class
XuanTung Hoang
14
Notices about static methods (cont.)

(1) If maximum() is called inside determineMax(),
maximum() is also called when determineMax() is called.

(2) If determineMax() is static, it can be called when no
objects are created.

(1), (2)  maximum( ) can be called when no objects are created.

Thus maximum( ) must be static
XuanTung Hoang
15
Notices about static methods (cont.)
Is it ok ?
public class MaximumFinder {
public
static double
maximum( double x, double y, double z) {
// code that finds the maximum value among
// x, y , and z
}
public
static
void determineMax() {
Scanner input = new Scanner( System.in );
double number1, number2, number3;
number1 = input.nextDouble();
number2 = input.nextDouble();
number3 = input.nextDouble();
double result = maximum( number1, number2, number3 );
}
}
XuanTung Hoang
16
Notices about static methods (cont.)
Is it ok ?
public class MaximumFinder {
public double maximum( double x, double y, double z) {
// code that finds the maximum value among
// x, y , and z
}
public
static
void determineMax() {
Scanner input = new Scanner( System.in );
double number1, number2, number3;
number1 = input.nextDouble();
number2 = input.nextDouble();
number3 = input.nextDouble();
MaximumFinder finder = new MaximumFinder();
double result = finder.maximum( number1, number2, number3 );
}
}
XuanTung
Hoang
17
Method Call Stack and Activation
Records


Read textbook, section 6.6
We will come back to this when we
discuss about Recursion
XuanTung Hoang
18
Argument Promotion and Casting

Do you remember type-casting and promotion?
int total = 0;
int gradeCounter;
// Loop that gets grade records
This is copied from
lecture 4
// Calculate average – case 1
average = total/gradeCounter; // WRONG result
// Calculate average – case 2
average = (double)total/gradeCounter;// Correct, explicit
// Calculate average – case 3
average = total*1.0/gradeCounter; // Correct, implicit
// definition of method sqrt() in class Math
public static sqrt( double a )
integer value for a
double argument !!
// you can call sqrt as follow
double result = Math.sqrt( 4 );
XuanTung Hoang
19
Valid Promotions for Primitive Type
Type
Valid promotions
double
float
long
int
char
short
byte
boolean
None
double
float or double
long, float or double
int, long, float or double
int, long, float or double (but not char)
short, int, long, float or double (but not char)
None (boolean values are not considered to be numbers in Java)
XuanTung Hoang
20
Explicit v.s. Implicit type conversion


Implicit type conversion (promotion) will
always follow the rules defined in the
previous slide
Explicit type conversion can break the rule someti
mes

E.g.:


float a = 5.4;
int b = (int) a; // b will be equal to 5
Explicit type conversion may change the value if the new type is not a valid
promotion.
XuanTung Hoang
21
Enumeration


Programmer-defined types
Representing a set (e.g. : Day of weeks: SUN, MON,
TUE, WED, THU, FRI, and SAT)
public class TestEnum {
public enum DayOfWeek {SUN, MON, TUE, WED, THU, FRI, SAT};
//...
public void method1( String args[] ) {
// ...
DayOfWeek today = DayOfWeek.SUN;
// ...
}
// ...
}
XuanTung Hoang
22
Enumeration (2)

Items in an enumeration can be considered as
constants
public class TestEnum {
public enum DayOfWeek {SUN, MON, TUE, WED, THU, FRI, SAT};
//...
public void method1( String args[] ) {
// ...
DayOfWeek today = DayOfWeek.SUN;
// ...
switch( today ) {
case SUN: System.out.println("Sunday"); break;
case MON: ...
// ...
}
}
// ...
}
XuanTung Hoang
23
Scope of Declarations

A declaration:



Field
Method
Scope of a declaration is the portion of the progra
m where the declared entity can be referred to usi
ng its name.
XuanTung Hoang
24
Scope Rules (1)

Rule 1: The scope of method’s parameters
public class TestScope {
//...
public void method1( int aNumber )
{
// ...
System.out.printf("aNumber = %d\n", aNumber);
// ...
}
// ...
}
Scope of parameter aNumber
XuanTung Hoang
25
Scope Rules (2)

Rule 2: The scope of local variables
public class TestScope {
//...
public void method2()
{
// ...
int var1;
// ...
System.out.printf("var1 = %d\n", var1);
// ...
}
// ...
}
Scope of local variable var1
XuanTung Hoang
26
Scope Rules (3)

Rule 2 (cont.)
public class TestScope {
//...
public void method2()
{
// ...
{
// ...
int var2;
// ...
System.out.printf("var2 = %d\n", var2);
}
// ...
}
// ...
}
Scope of local variable var2
XuanTung Hoang
27
Scope Rules (4)

Rules 3: Scope of a local-variable and for loops
public class TestScope {
//...
public void method3()
{
// ...
for( int i = 0; i < 10; i++ )
{
// ...
System.out.printf("i = %d\n", i);
// ...
}
}
// ...
}
Scope of local variable i
XuanTung Hoang
28
Scope Rules (5)

Rule 4: The scope of methods and fields
public class TestScope {
private int field1;
public void method2() {
// ...
System.out.printf( "field1 = %d\n", field1 );
// ...
}
// ...
public void method3() {
// ...
System.out.printf( "field1 = %d\n", field1 );
// ...
method2();
}
}
Scope of methods and fields is the entitle class
XuanTung Hoang
29
Scope: Shadowing

A variable (or field) in outer scope can be shadowed by another variabl
e (or field) of the same name in inner scope
// ...
int number1;
// ...
number1 = 2;
// ...
{
int number1 = 6
System.out.printf( "number1 = %d\n", number1 ); //number1 = 6
// ...
}
System.out.printf( "number1 = %d\n", number1 ); //number1 = 2
// ...
Inner scope
Outer scope
XuanTung Hoang
30
Scope: shadowing example
public class ShadowingDemo {
private int var1;
public ShadowingDemo( int v ) {
var1 = v; // Initialize field var1 to v
}
public void testShadowing() {
int var1 = 4;
System.out.printf("This is local variable var1:%d\n", var1 );
}
public int getVar1() {
return var1;
}
public static void main(String args[]) {
ShadowingDemo shadow = new ShadowingDemo( 7 ); // field var1 = 7
shadow.testShadowing();
// test field var1
System.out.printf("This is field var1: %d", shadow.getVar1() );
}
}
XuanTung Hoang
31
Scope: Shadowing - Questions
public class ShadowingDemo {
Modify
private int var1;
ShadowingDemo
public ShadowingDemo( int v ) {
var1 = v; // Initialize field var1 to v
}
public void testShadowing() {
int var1 = 4;
System.out.printf("This is local variable var1:%d\n", var1 );
}
public int getVar1() {
return var1;
}
public static void main(String args[]) {
ShadowingDemo shadow = new ShadowingDemo( 7 ); // field var1 = 7
shadow.testShadowing();
// test field var1
System.out.printf("This is field var1: %d", var1 );
}
}
Problem?
XuanTung Hoang
32
Scope: Shadowing - Questions
public class ShadowingDemo {
Modify
private int var1;
ShadowingDemo
public ShadowingDemo( int v ) {
var1 = v; // Initialize field var1 to v
}
public void testShadowing() {
int var1 = 4;
System.out.printf("This is local variable var1:%d\n", var1 );
}
public int getVar1() {
return var1;
}
public static void main(String args[]) {
ShadowingDemo shadow = new ShadowingDemo( 7 ); // field var1 = 7
shadow.testShadowing();
// test field var1
System.out.printf("This is field var1: %d", getVar1() );
}
}
Problem?
XuanTung Hoang
33
Method Overloading

Method overloading: multiple methods with the s
ame name can coexist in one class

Example: in class Math, we have 4 versions of method
min()
public static double min( double x1, double x2 )
Method
is combination
of method
publicsignature
static float
min( float x1,
float x2 )
name
andstatic
the number,
andint
order
public
int min(type,
int x1,
x2 )of its
arguments
public static long min( long x1, long x2 )
Methods are distinguished by their signatures,
not by their names
XuanTung Hoang
34
Pass-by-value v.s. Pass-by-reference
public class TestPassByVal {
public static void main( String args[] ) {
int a = 4;
System.out.println( "a = " + a );
test( a );
System.out.println( "a = " + a );
}
public void test( int val ) {
val += 5;
System.out.println( "val = " + val );
}
}
a = 4
val = 9
a = 4
XuanTung Hoang
Method test() modify
value of the
argument that is
passed to it. But the
original value doesn’t
change
Pass-by-value: the
argument is just a
copy of the original
variable
val is a copy of a
35
Pass-by-value v.s. Pass-by-reference
public class MyInteger {
private int number;
public MyInteger( int a ) { number = a; }
public int getVal() { return number; }
public void setVal( int a ) { number = a; }
}
public class TestPassByRef {
public static void main( String args[] ) {
MyInteger a = new MyInteger(4);
System.out.println("a = " + a.getVal());
test( a );
System.out.println("a = " + a.getVal());
}
public void test( Integer val ) {
val.setVal( val.getVal() + 5 );
System.out.println("val = " + val.getVal() );
}
}
a = 4
val = 9
a = 9
XuanTung Hoang
Method test() can
modify the object
accessed via the
argument
Pass-by-reference:
the argument is a
reference to some
object. Thus, the
object can be altered
by the method
val is a copy of a, but
val and a all refer to
the same object
36
Argument passing in Java


If an argument is an object, pass-by-reference is
used
If an argument is of a primitive type, pass-byvalue is used
XuanTung Hoang
37
Java API Packages

Lots Import
of available
classesclass:
in JDK. They are grouped in pac
a specific
kages







E.g.: import java.util.Scanner;
java.io: Input/Output classes and interfaces
java.util:
Utility
classes and
Import
all classes
ofpackets
a package
java.net: Networking Package
E.g.: import java.util.*;
javax.swing and java.awt: for GUI
java.applet: Applet Packages
Explicitly use a class (without import)
java.lang: fundamental classes and interfaces
(don’t needE.g.:
to import)
java.util.Scanner input =
See more:
new java.util.Scanner(System.in);


Section 6.8, textbook
http://java.sun.com/j2se/1.5.0/docs/api/overview-summary.html
XuanTung Hoang
38
Some useful classes

String (in java.lang)

Declaration/initialization:



String concatenation:




String str = “this is a string”;
String str = new String(“this is a string”);
String str1 = “The number is”;
String str2 = “ too long”;
String str = str1 + str2;
int x = 11;
String str1 = “value of x is ” + x;
int x = 11, y = 1;
String str = “value of x + y” + (x + y);
See more at javaAPI manual
XuanTung Hoang
39
Some useful classes (cont.)

Primitive type wrapper: Integer, Long, Double,
Float, … (in java.lang)

Declaration/Initialization:



Get internal value


Integer oInt = new Integer(13);
int x = oInt.intValue();
double d = oInt.doubleValue();
...
Parse a string to a numeric value


Integer oInt = new Integer(13);
Integer oInt = new Integer(“13”);
String str1 = “123”;
int x = Integer.parseInt(str1);
See more in javaAPI manual
XuanTung Hoang
40
Related documents