Download Methods

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
Methods
Outline #313#9 #212#9
Introducing Methods
Overloading Methods
Scope of Variables
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
4/65
1
Reserved Words
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
5/65
Methods?
• The simplest programs consist of the class
header and the main method which consists of a
few statements
• A more sophisticated programs consists of
control structures such as if, for, switch etc.
• Once the length of a program becomes larger, it
becomes harders to manage whole program in
one part
• In this point, methods help.
• Methods are mainly the structures which allow
us divide a large program into smaller pieces and
write them seperately, and then combine them to
build the whole piece
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
6/65
2
Benefits of using Methods
• Dividing a large program into smaller pieces
§ Either to solve the problem by smaller pieces, or to
allow many programmers write parts of the same
program
• Writing a method to solve a problem, and using it
in many places
• Hiding the implementation of a specific process,
thus easing project development
• Object oriented concept forces using methods,
so that without methods there would be no OOP
7/65
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
Method Abstraction
• Method header is visible to every program, and
accessable w.r.t. the visibility modifier (public,
private, protected)
• Method body is not visible, and the method body
can be thought as a black box
Method header
Method body
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
visible
black box
8/65
3
Method Declarations
• A method declaration specifies the code that will
be executed when the method is invoked (called)
• When a method is invoked, the flow of control
jumps to the method and executes its code
• When complete, the flow returns to the place
where the method was called and continues
• The invocation may or may not return a value,
depending on how the method is defined
9/65
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
Method Control Flow
• If the called method is in the same class, only the
method name is needed to call it
compute
myMethod
myMethod();
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
10/65
4
Method Control Flow
• The called method is sometimes part of another
class or object
main
doIt
helpMe
helpMe();
obj.doIt();
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
11/65
Method Header
Declaring a (non-void) method:
modifier
method
header
method
body
return
value
type method name formal parameters
public static int total(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
Calling (invoking) a method:
actual parameters
int z = total( a, b );
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
12/65
5
Method header
• A method header consists of
§
§
§
§
the modifier(s) of the method (public, private, ...)
return type (void, int, ...)
method name (max, calculate, ...)
parameter type list (int x, float y, ...)
• The method signature consists of
§ method name
§ parameter type list
13/65
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
Method Body
• The method header is followed by the method
body
char calc (int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt (sum);
return result;
sum and result
The return expression
must be consistent with
the return type
They are created
each time the
method is called, and
are destroyed when
it finishes executing
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
are local data
14/65
6
Nested Methods?
• Nested methods are not allowed in java
public static void main( String[] args ) {
public static int add( int a, int b ) {
return a + b;
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
15/65
Parameter type
• Type of each individual parameter must be
declared individually
public static int add( int a, b ) {
return a + b;
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
16/65
7
Parameters
•
The variables defined in the method header are
known as formal parameters.
•
When a method is invoked, you pass a value to
the parameter. This value is referred to as actual
parameters.
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
17/65
Parameters
• When a method is called, the actual parameters in
the invocation are copied into the formal
parameters in the method header
ch = obj.calc (25, count, "Hello");
char calc (int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt (sum);
return result;
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
18/65
8
return Statement
• The return type of a method indicates the type of
value that the method sends back to the calling
location
• A method that does not return a value has a void
return type
• A return statement specifies the value that will be
returned
return expression;
• Its expression must conform to the return type
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
19/65
Return
• This is a valid usage for return:
public static int total(int x, int y)
{
return (x + y);
}
• This is also a valid usage for return:
public static int total(int x, int y)
{
int sum = x + y;
return sum;
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
20/65
9
Statements after return:
• When a return statement is executed, all further
statements are to be omitted
• Last statement will be omitted in the following
code:
public static int total(int x, int y)
{
int sum = x + y;
return sum;
System.out.print( “Total = “ + sum );
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
21/65
return in conditional statements:
• return statements can also be included in
conditional statements (if, switch...)
public static int max(int x, int y) {
if ( x > y )
return x;
else
return y;
}
• Alternative code:
public static int max(int x, int y){
int m;
if ( x > y )
m = x;
else
m = y;
return m;
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
22/65
10
return in conditional statements:
• When return statements are included in a
conditional statement, then all alternatives should
return a value
• Error:
public static int max(int x, int y){
if ( x > y )
return x;
else
x = y;
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
23/65
Caution
• return statement is required for a nonvoid
methods.
• The following method is logically correct, but it
has a compilation error. Why?
public static int sign(int n) {
if (n > 0) return 1;
else if (n == 0) return 0;
else if (n < 0) return –1;
}
• Because the Java compiler thinks it is possible
that this method does not return any value
• Solution?
§ delete
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
24/65
11
Returning values
• Methods which are declared as void does not
return any value
public static void say( String message ){
System.out.print( message );
}
• void methods are invoked as a statement and can
not be used as a value
say( “Hello” );
String message = “Hello”;
say( message );
• Following usage is wrong!
String message = say( “Hello” );
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
25/65
Void.java
public class Void {
public static void main( String[] args ) {
say();
}
public static void say(){
System.out.print( “Hello :-)" );
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
26/65
12
Test Void Method
public class TestVoidMethod {
public static void main( String[] args ) {
printGrade( 78 );
}
public static void printGrade( int score ) {
if ( score >= 90 )
System.out.print( ‘A’ );
else if ( score >= 80 )
System.out.print( ‘B’ );
else
System.out.print( ‘F’ );
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
27/65
non-void methods
• Methods which return a value are referred as
non-void methods
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
28/65
13
Invoking void and non-void methods
• void methods are written as a statement
displayAll( a, b );
respond();
• non-void methods are to be used as a value
result = total( a, b );
System.out.print( total( a, b ) );
29/65
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
Parameter match
public static void main(String[] args) {
int i = 1, j = 2;
int k = add( i , j );
System.out.print( “ Total = “ + k );
3
1
2
public static int add( int x , int y ) {
return x + y;
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
30/65
14
Invoking methods
•
•
One of the benefits of methods is invoking it from other
classes as well as from the same class
Methods can be invoked:
1. from the same class by:
methodName
2. from other classes by either:
ClassName.methodName
objectName.methodName
Example:
§
max method can be invoked from the TestMax by:
max(
,
)
§
max method can be invoked from other classes by:
TestMax.max(
,
)
test.max(
,
)
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
31/65
Void.java & OtherClass.java
• Void.java
public class Void {
public static void main( String[] args ) {
say();
}
public static void say(){
System.out.print( “Hello :-)" );
}
}
• OtherClass.java
public class OtherClass {
public static void main( String[] args ) {
Void.say();
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
32/65
15
Exam #313#11
Exam #313#12
Exam #202#11
Exam #202#12
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
33/65
Outline #313#13
Introducing Methods
Overloading Methods
Scope of Variables
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
34/65
16
Object – Oriented Concepts
•
There are 3 main properties of Object – Oriented
Environments
1. Inheritance
2. Overloading
3. Polymorphism
•
Every Object – Oriented Environment should
support them
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
35/65
Overloading methods
• The add method used previous example uses two
int parameters
• What if we want to add two double values?
§ We would declare another max method with
double parameters
• Java allows using same name for two or more
methods
§ requiring that types of variables does not
completely match
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
36/65
17
Overloading example
public class Overloading {
public static void main(String[] args) {
System.out.println(add(1, 2));
System.out.println(add(1.0, 2.0));
}
public static int add(int x, int y) {
return( x + y );
}
public static double add(double x, double y) {
return( x + y );
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
37/65
Ambiguity
• Sometimes there may be two or more possible
matches for an invocation of a method, but the
compiler cannot determine the most specific
match.
• This is referred to as ambiguity.
• Ambiguous definition is a compilation error.
• To get rid of ambiguity in method definition, all
method signatures should be different in that
class
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
38/65
18
Overloading vs. Ambiguity
• Overloading: methods with the same name but
different signature
int add( int a, int b ) {...} ;
int add( float a, int b ) {...} ;
• Ambiguity: methods with the same name and
same signature
int add( int a, int b ) {...} ;
int add( int a, int b ) {...} ;
39/65
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
Ambiguous Methods - 1
public class Ambiguous
{
public static void main (String[] args)
{
...;
}
public static int max( int num1) {
...;
return ...;
}
public static int max( int num2) {
...;
return ...;
}
Error
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
40/65
19
Ambiguous Methods - 2
public class Ambiguous
{
public static void main (String[] args)
{
...;
}
public static void max( int num1) {
...;
return ...;
}
public static int max( int num2) {
...;
return ...;
}
Error
}
41/65
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
Non-ambiguous Methods
public class NonAmbiguous {
{
public static void main (String[] args)
{
...;
}
public static int max( char num1 ) {
...;
return ...;
}
public static int max( int num2 ) {
...;
return ...;
}
Correct
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
42/65
20
Ambiguous Methods - 1
public class Overloading {
//overloading
static int add(int num1, int num2) {
return( num1 + num2 );
}
//overloading
static double add(double num1, double num2) {
return( num1 + num2 );
}
//ambiguity, not allowed
static void add(int num1, int num2) {
System.out.println(add(1, 2));
}
//ambiguity, not allowed
static void add(double num1, double num2) {
System.out.println(add(1, 2));
}
public static void main(String[] args) {
System.out.println(add(1, 2));
System.out.println(add(1.2, 2.2));
add(1, 2);
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
43/65
Outline
Introducing Methods
Overloading Methods
Scope of Variables
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
44/65
21
Scope of Variables
• Scope: the part of the program where the
variables can be referenced.
• Variables can be either:
§ Global (to the class)
§ Local
• To the method
• To the block statement
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
45/65
Global variable
• Global variable: a variable defined just after the
header of a class
• The scope of a global variable is the whole class
public class Calculate {
int k;
public static void main( String[] args ) {
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
46/65
22
Local Data
• As we’ve seen, local variables can be declared
inside a method
• The formal parameters of a method create
automatic local variables when the method is
invoked
• When the method finishes, all local variables are
destroyed (including the formal parameters)
• Keep in mind that instance (global) variables,
declared at the class level, exists as long as the
object exists
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
47/65
Local Variable
• Local variable: a variable defined inside
§ a method, or
§ a block
• The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable
public class Calculate {
int k;
public static void main( String[] args ) {
int i;
for ( int m = 0; m < k; m++ )
{
i = 5;
int j = 0;
}
i = 6;
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
48/65
23
Visibility in Blocks
• When we locate the blocks in all cases, we can
easily see that actually there is only one rule:
§ Visibility of a variable starts with the
declaration, and ends with the end of the block
public class Calculate { //block1
int k;
public static void main( String[] args ) { //block2
int i;
for ( int m = 0; m < k; m++ ) { //block3
i = 5;
int j = 0;
} //block3
i = 6;
} //block2
} //block1
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
49/65
Visibility in Blocks
• Actually we may make a projection of all cases
into blocks
• All of the places where a variable may be declared
is actually inside a block
public class Calculate {
int k;
......
}
public static void main( String[]args ) {
int x;
......
}
for ( int i = 0; i < MAX; i ++ ) {
int y;
......
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
50/65
24
Visibility in Blocks
• Actually scope of local and global variables are
same, and they
§ start with the declaration,
§ end with end of the block
• All variables are declared within a block
statement:
§ Global variables are declared within block of
class,
§ Local variables are declared either within:
• block of a method,
• block of a block statement
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
51/65
Using a name for a variable
• When declaring a varialble, you can use name if a
–previos- variable defined elsewhere if:
§ The scope of the previous variable does not
extend to the place of the new declaration
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
52/65
25
Declaring Variables
• You can declare two or more variables with the
same name within a program, but:
§ No variable can be defined in the scope
(visible area) of the other variable
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
53/65
Scope of variables
• The scope of variables is the area in a program in
which that data can be referenced (used)
• Data declared at the class level (immediately after
the class header, before method definitions) is
called global (global to the class) can be
referenced by all methods in that class
• Data declared within a method is called local (local
to that method) and can be used only in that
method
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
54/65
26
Scope
public class MyProgram
{
global definitions
can be accessed anywhere in the class
public int setFaceValue()
{
local definitions
can be accessed only within this method
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
55/65
Local vs. Global Variables
public class Calculate {
int k = 1;
public static int total(...)
{
char c = ‘a’;
.
for ( int i = 1; i < 10; i++ )
{
.
local variables
.
int j = 2;
.
.
}
}
}
global variable
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
56/65
27
Scope of Local variables
• A variable declared in the initial action part of a loop header
has its scope in the entire loop.
• But a variable declared inside a loop body has its scope
limited in the loop body from its declaration and to the end
of the block that contains the variable.
scope
of i
public static int total(...)
{
.
.
for ( int i = 1; i < 10; i++)
{
.
.
int j;
scope
.
of j
.
}
}
57/65
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
Scope of local variables
• An obvious result of scope definition os that a
variable defined in a method can not be referred
in another
public class TestScope {
public int method1 {
int x = 0;
....
}
public int method2 {
System.out.print( x );
....
}
}
Error
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
58/65
28
Scope of for loop – 1
public class TestForScope
{
public static void main ( String[] args )
{
int count = 0;
System.out.println (count);
for ( int count = 1; count <= 5; count++)
System.out.println (count);
System.out.println (count);
for (int j = 1; count <= 5; count++)
System.out.println (count);
int j = 0;
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
59/65
Scope of for loop – 2
public class TestForScope
{
public static void main ( String[] args )
{
int count = 0;
System.out.println (count);
for ( /*int*/ count = 1; count <= 5; count++)
System.out.println (count);
for (int j = 1; j <= 5; j++)
System.out.println( j );
int j = 0;
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
60/65
29
Scope of Local Variables
public static void method1() {
int x = 1;
int y = 1;
for ( int i = 1; i < 10; i ++ ) {
x += i;
}
Ok
to declare
i in two
non-nesting
blocks
Wrong
to declare
i in
nesting
blocks
for ( int i = 1; i < 10; i ++ ) {
y += i;
}
public static void method2() {
int i = 1;
int sum = 0;
for ( int i = 1; i < 10; i ++ ) {
sum += i;
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
61/65
Scope of Local Variables
public class TestScope
{
public static void main ( String [] args )
{
for ( int x = 1; x < 9; x++ ) {
System.out.print ( x );
}
System.out.print ( x );
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
62/65
30
Scope of Local Variables
public class TestScope
{
public static void main ( String [] args )
{
int x;
for ( x = 1; x < 9; x++ ) {
System.out.print ( x );
}
System.out.print ( x );
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
63/65
Scope of Local Variables
public class TestScope
{
public static void main ( String [] args )
{
int y;
for ( int x = 1; x < 9; x++ ) {
System.out.print ( x );
y = x;
}
System.out.print ( y );
}
}
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
64/65
31
Scope of Local Variables
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}
Error
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
65/65
Passing values to a method
• Any number of values can be passed to the
method by way of parameters
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
66/65
32
Returning values from a method
•
•
•
Only one value can be returned from a method
by the return statement
Assume that we want to find a minimum and
maximum values of an array. Can we return
both values from the same method?
Two options:
1. The method may return an array with both values
2. Use the memory as the buffer
• Write values to the memory within the method
• Read values from the memory after the method
returns
Dr.Vedat Coşkun – Summer School 2006 - Object Oriented Programming with Java
67/65
33