Unit_3_-_Methods
Unit_3_-_Methods
Unit 3 - Methods
Faculty of Computer Science 2009
Universitas Indonesia
Objectives
• Methods
• Hiding the Implementation
• Package and Classpath
• Java Access Specifier
• JavaDocs
1
2/25/2009
Java Implementation
import java.util.Scanner;
public class ExampleOne
{
public static void main( String args[])
{
int x, y;
double mean;
String outString;
Scanner input= new Scanner(System.in);
System.out.print(“Enter an integer “);
x = input.nextInt();
System.out.print(“Enter an integer “);
y = input.nextInt();
mean = calculateMean( x, y);
outString="Mean of " + x + " & " + y +
" is " + mean;
System.out.println( outString);
}
2
2/25/2009
Invoking a method
• When a method is invoked, an expression must
be provided for each matching parameter in
the desired method.
• Remember that an expression can be:
– A literal constant (e.g. 42);
– A named constant (e.g. Math.PI)
– A variable (e.g. lifeTheUniverseAndEverything).
– The return value of a functional method (e.g.
Math.sin()).
– A combination of all of the above joined together with
a valid set of operators (e.g. Math.PI/180.0).
• When the method is invoked:
– each expression is evaluated
– the result is passed onto the method
– the method becomes the active module.
3
2/25/2009
Method Parameters
• Variables declared to be local to a method can
be:
– declared inside the method block or
– declared as a method parameter.
• The difference is that:
– the parameter variables get their initial values from
the calling method
– the others are auto initialised (although good
programming practice means that we should
explicitely initialise these variables).
Example
4
2/25/2009
5
2/25/2009
Object Communication
Constructors
• Constructors are the methods used to
create an object (i.e. to create an
instance of a class).
• There may be several constructors
available.
• This is to allow the object to be created
in a variety of different ways.
• Overloading is used to select the correct
constructor.
• Example:
– An picture class which can be constructed:
• As a blank image ( number of rows and columns
supplied to the constructor).
• Read from a file (filename supplied to the
constructor).
6
2/25/2009
7
2/25/2009
8
2/25/2009
Example
public class TimeClass
{
private int hours, mins, secs,
elapsedmins, elapsedsecs;
. . .
public int getHours()
{
return hours;
}
public int getMinutes()
{
return mins;
}
public int getSeconds()
{
return secs;
}
}
9
2/25/2009
void Methods
• void is used to specify that this method
does not have a return value.
• In non OO languages:
– C: void function.
– Pascal: procedure
– Fortran:subroutine
– COBOL:paragraph
• Used for doing and Mutator methods.
10
2/25/2009
11
2/25/2009
Example
public void setHours( int h)
{
if ( h >= 0 )
{
hours = h;
calculateElapsed();
}
}
public void setMinutes( int m)
{
if (( m >= 0 )&&( m < 60 ))
{
mins = m;
calculateElapsed();
}
}
public void setSeconds( int s)
{
if (( s >= 0 )&&( s < 60 ))
{
secs = s;
calculateElapsed();
}
}
Doing Methods
12
2/25/2009
13
2/25/2009
Example
public class Time // Test harness
{
public static void main( String args[])
{
TimeClass mytime = new TimeClass( 10,
20, 32);
TimeClass yourtime;
mytime.displayTheTime();
yourtime = new TimeClass();
yourtime.setHours( 14);
yourtime.setMinutes( 45);
System.out.println( "Elapsed Minutes
is " + yourtime.getElapsedMinutes());
}
}
Private Methods
• These are the methods that are used
within the object but are never seen by
the outside world.
• They are hidden so that they can be
modified or even replaced without
causing problems in any other part of
the software.
• To perform a complex task, it is often
easier to break the task down into a
series of sub-tasks and then refine each
sub task independently of the others.
• This process is known as step wise
refinement.
14
2/25/2009
Method Overloading
• Method Overloading is the mechanism used to:
– Provide a variety of different possibilities within the
same class.
– Provide a different implementation to an equivalent
method in the super class(es).
• The Method name and the arguments used is
known as the Method’s signature.
• In Java it is implemented by matching the
signature of the method call with the various
possible signatures for the method.
• Where a method has the same input
arguments and the same return values in both
the parent and the sub class, the sub class
method will be the one selected.
Example
15
2/25/2009
16
2/25/2009
17
2/25/2009
18
2/25/2009
19
2/25/2009
Constants in Java
20
2/25/2009
21
2/25/2009
Passing Objects
• Consider the calling method:
DateClass d1, d2;
...
d1 = fred.getDOB1();
d1.setDate( 2, 2, 2002);
d2 = fred.getDOB2();
d2.setDate( 2, 2, 2002);
• Because the getDOB1() method returns a
reference to the class field within fred then the
call to setDate will cause the object refered to
by the class field to mutate. i.e. I have
modified the contents of a private variable
from outside the object!
• d2 will get the reference to a complete copy of
the object referred to by the class field and
hence the modification will only happen to the
copy.
22
2/25/2009
23
2/25/2009
24
2/25/2009
Library
25
2/25/2009
26
2/25/2009
27
2/25/2009
28
2/25/2009
Classpath
• As you might guess (because our
programs have worked!), the
classpath by default includes the
current directory
• Directories and .jar files in the
classpath are searched for .class
files
• .jar files that are in a directory that's
in the classpath are not treated as
being in the classpath. You need to
explicitly put a .jar file in your
classpath.
29
2/25/2009
Classpath
• classpath is an environment
variable that can be set in the OS
before running the JVM
set classpath=.\;C:\StudentWork
• -classpath is a command-line
option for the Java utilities
including java.exe
java -classpath .\;C:\StudentWork x
• Blanks are delimiters here, so you
will NOT want blanks in your
directory names
30
2/25/2009
Exercise
31
2/25/2009
Exercise
• Take your homework assignment
which consists of several classes
• Put them all in the same package
• Compile them
– They should end up in the same
subdirectory
• Use jar.exe to create a jar file:
jar -cvf <name>.jar
<subdir>\*.class
• Execute your program from the jar
java -classpath <name>.jar
<package>.<class>
32
2/25/2009
Collisions
• What happens if two libraries are
imported and they include the same
names?
– package java.util has a Date
– so does java.sql
• If you don't use any Date, you're fine
• If you do, you need to specify which
one
java.util.Date dt = new
java.util.Date();
33
2/25/2009
Package Caveat
34
2/25/2009
Friendly
35
2/25/2009
36
2/25/2009
Private constructors
public class Connection {
private Connection me = null;
private Connection() {}
public static Connection getConnection(){
if (me == null)
me = new Connection();
return me;
} // end getConnection
} // end class Connectionpublic
class ConnectToServer {
public static void main(String[] args) {
//! Connection conn = new Connection();
Connection c =
Connection.getConnection();
} // end main
} // end class ConnectToServer
37
2/25/2009
Class Access
Class Access
38
2/25/2009
JavaDocs
• When you generate javadocs, you
specify which access levels you want
documentation for
• This is a convenience for the client
programmers, as it means they see
only what they can use
• If you are going to work on a class,
you can always run the full javadocs
on your own machine
DateClass.java
public class DateClass
{
private int day, month, year;
public DateClass() // default
{
day = month = 1; year = 2000;
}
public DateClass( int day, int month, int year)
{
if ( isValidDate( day, month, year))
{
this.day=day;this.month=month;
this.year=year;
}
else
{
this.day = this.month = 1;
this.year = 2000;
}
}
39
2/25/2009
DateClass.java
public setDate( int day, int month,
int year)
{
if ( isValidDate( day, month,
year))
{
this.day=day;
this.month=month;
this.year=year;
}
}
public String toString()
{
return new String ( day + "/" +
month + "/" + year);
}
DateClass.java
public int getDay()
{
return day;
}
public int getMonth()
{
return month;
}
public int getYear()
{
return year;
}
40
2/25/2009
DateClass.java
DateClass.java
private int daysInMonth(int month, int year)
{
int numDays;
switch( month )
{
case 4: case 6: case 9: case 11:
numDays = 30; break;
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
numDays = 31; break;
default: // must be feb
if ( isALeapyear( year)
numDays = 29;
else
numDays = 28;
} // end switch
return numDays;
}
41
2/25/2009
DateClass.java
TestDateClass.java
import io.*;
public class TestDateClass
{
public static void main( String [] args)
{
DateClass date1, date2;
date1 = new dateClass( 10, 4, 1996);
date2 = new dateClass();
OutputDialog.output("Date1:" + date1.toString());
OutputDialog.output("Date2:" + date2.toString());
for(int year=1999; year <= 2100; year++)
for( int month=1; month<=12;month++)
for(int day=0; day<=32;day++)
{
date1.setDate( day, month, year);
System.out.println("Attempted to set :" +
day + "/" + month + "/" + year +":::::");
System.out.println("Date set to: " +
date1.toString());
} // end for
} // end main
} // end class
42