0% found this document useful (0 votes)
5 views

Unit_3_-_Methods

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit_3_-_Methods

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

2/25/2009

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

Methods are Sub-Modules


• Sub modules are used to
compartmentise an algorithm.
• Java Methods are the implementation of
a sub module.
• A contract is the agreement between the
sub module and the outside world (i.e.
the rest of the algorithm).
• A contract consists of:
– IMPORT: Information which is supplied to
the sub module.
– EXPORT: Information that the sub module
will pass back to the calling sub module.
– Assertions: facts that will be true after the
sub module has been executed.

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

Java Implementation (Cont..)


//SUB MODULE calculateMean
//IMPORT: a and b
//EXPORT: mean
//Assertion:mean will be average
of a and b
public static double
calculateMean( int a, int b)
{
return (double)(a + b)/ 2.0;
}
} // end class

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).

public void exampleOfAMethod( int paramOne,


float paramTwo)
{
int localOne;
float localTwo;
. . .;
}

Example

4
2/25/2009

Characteristics of Method Parameters


• Each parameter is initialised with the
result of the matching expression in the
method call.
• Parameters are local variables which
means that each parameter has no
knowledge as to where its initial value
came from.
• A modification to the value of a
parameter will have no effect on the
value of the corresponding argument in
the calling module.

Exception to the Rules


• Non OO programming languages (and
some OO languages) have a second
way of defining parameters. This second
way is called passing by reference.
• In Java there are two data types which
must be passed by reference:
– References to objects.
– Arrays (a special type of object. See later).
• A variable which has been declared as
being a particular class type will contain
the address of the object (a reference to
the object).
• Any modification to the object will be
reflected in the calling module!

5
2/25/2009

Object Communication

• Sometimes referred to as message passing.


• A class definition will consist of some variables
and some methods.
• The variables will represent whatever
information is required in a form that is hidden
from the outside world.
• There are five categories of methods:
– The Constructors.
– The Accessor Methods (aka Interrogative Methods).
– The Mutator Methods (aka Informative Methods).
– Doing Methods (aka Imperative Methods).
– Private methods.

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

Accessor / Interrogative Methods


• Accessor methods are used to retrieve
information from the object.
• Accessor methods clearly define the
data types of the information to be
retrieved from the object.
• Each Accessor method should retrieve
exactly one piece of data.
• Example:

Classes in Java: Accessor Methods

• Accessor methods are implemented as public


methods whose return types are compatible
with the data being passed out of the object.
• The mechanism for sending the information out
of the method is to use the return statement.
• The syntax is return expression;
• Where expression must be compatible with the
return type of the method (e.g. a method which
returns a double must have a double
expression in its return statement.
• Java does not place any constraints on where
or how many return statements are provided
within a method.

7
2/25/2009

Correct Use of the return Statement

• Java does not place any constraints on:


– where in a method the return statement is placed.
– how many return statements a method can have.
• Good programming practice means that every
non−void method:
– will have exactly one return statement.
– the return statement will be the last statement in the
method.
– the return statement will have an expression which is
compatible with the data type specified in the header
of the method.
• void methods are methods which do not return
any kind of value to the calling method (see
later).

Incorrect Use of the return Statement

public boolean isEven( int number)


{
if ( number % 2 == 0 )
return true;
else
return false;
}

8
2/25/2009

Correct Use of the return Statement

public boolean isEven( int number)


{
boolean evenOrNot;
if ( number % 2 == 0 )
evenOrNot = true;
else
evenOrNot = false;
return evenOrNot;
}

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

The toString() Method

• A Java convention is for every class to


have a toString() accessor method
which returns a String object.
• TimeClass Example:
public String toString()
{
String timeStr;
timeStr = new String("Time is "
+ hours + " hrs " + mins +
" mins ” + secs + " secs");
return timeStr;
}

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.

public void sayHello()


{ System.out.println(“Hello!”);
}

10
2/25/2009

Mutator / Informative Methods


• Mutator methods are used to send information
into the object. In other words this new
information mutates the state of the object.
• Mutator methods clearly define the data types
of the information to be passed into the object.
• The actual representation of the information
within the object is hidden.
• The data which is supplied to the method may
be a direct reflection of variables in the object
but this does not have to be the case.

Classes in Java: Mutator Methods

• Used for passing information into an


object.
• Currently implemented as void methods
but we could also implement them as
boolean methods. Any guesses as to
why?
• A good object design will strike a
compromise between the total number
of mutator methods and the range of
ways in which information can be
passed into the object.

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

• The methods are used for performing


some required task.
• For example, a method which output
information to the user would be
classified as a doing method.

12
2/25/2009

Classes in Java : Doing Methods


• Used to perform some part of the functionality
of the object.
• Could be private or public depending upon
requirements.
• Example:
public void displayTheTime()
{
String timestr;
timestr = new String("Time is " + hours + "
hrs “ + mins + " mins ” + secs + " secs");;
System.out.println( timestr);
}
private void calculateElapsed()
{
elapsedmins = hours * 60 + mins;
elapsedsecs = elapsedmins * 60 + secs;
}

Classes in Java : Golden Rules


• Each class in its own .java file.
• Put the main method in a class by itself. The
name for that class will be the name of the
application.
• All variables are private.
• Methods are categorised as public or private
and declared as such.
• Order your Java code consistently. Declare the
components of each class in the following
order:
– Declarations for variables which are global to the
class.
– Declarations for the Constructors.
– Accessor methods.
– Mutator methods.
– Doing methods (public).
– Private methods.

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

Simple Example: Initial Design


• Lets Consider a simple example, a class
for storing and retrieving the date.
• Decide on Accessors and Mutators first:
– getDay/setDay
– getMonth/setMonth
– getYear/setYear
– getDate/setDate
• Also Constructors:
– Default (with a default date (1/12000?)
– with day, month, year as parameters.
• The above suggests three class fields.
i.e. day, month and year.

Simple Example: Error Checking


• Accessors are easiest.
– They will all assume that the day, month and year have
been set already.
– getDay, getMonth and getYear will all return an integer
representing day, month and year.
– getDate will simply build a String of the form
day/month/year.
• Mutators are also easy, provided no error checking is
required.
• They will each import an integer specifying day, month
and year respectively and simply use that value to set
the appropriate field.
• Error checking adds a twist:
– We cannot error check day without knowing the month
and year.
– We cannot control the order in which the mutators are
called so it is possible that setDay is called before setMonth
and setYear.
• Conclusion: Remove setDay, setMonth and setYear from
design.

16
2/25/2009

Simple Example: Constructors


• Here is the revamped design:
– Class Fields:day, month and year
– Constructors:
Default:
day = 1, month = 1, year = 2000
Other:
IMPORT: newDay, newMonth and newYear
Assertion: If date is valid then it is set
otherwise date is set to 1/1/2000.
Algorithm:
IF isValidDate<--newDay,newMonth,newYear THEN
day = newDay, month = newMonth and year =
newYear
ELSE
day = 1, month = 1, year = 2000
ENDIF

Simple Example: isValidDate


• Stepwise refinement means we have to design
a sub module for validating the date:
• IMPORT: day, month, year
• EXPORT: validDate
• Assertion: validDate will be true if date is valid
and false otherwise
• Algorithm:
validDate = false
IF year between 1900 and 2000 inclusive THEN
IF month between 1 and 12 inclusive THEN
IF 1 <= day <= daysInMonth<--month,year THEN
validDate = true
ENDIF
ENDIF
ENDIF

17
2/25/2009

Simple Example: daysInMonth


IMPORT: month and year
EXPORT: numDays
Assertion: numDays will be the correct
number of days in month.
Assumes that month and year are valid.
Algorithm:
IF month is 4, 6, 9 or 11 THEN
numDays = 30
ELSE IF month is 1, 3, 5, 7, 8, 10 or 12 THEN
numDays = 31
ELSE
IF isALeapYear<--year THEN
numDays = 29
ELSE
numDays = 28
ENDIF
ENDIF

Simple Example: Mutator


• Mutator: setDate
• Import: newDay, newMonth and
newYear
• Export: Nothing
• Assertion: If day, month and year are
valid then reset date.
• Otherwise do not change date.
• Algorithm:
IF isValidDate<--newDay, newMonth,
newYear THEN
day = newDay, month = newMonth
and year = newYear
ENDIF

18
2/25/2009

Simple Example: Conclusion


• The accessors can stay as initially
described.
• Our object could be much more flexible:
• accessor which retrieves the date in a
variety of formats:
– day/month/year
– dayth of month, year
– Mutator which allows month parameter to
be a String or an Integer.

Final Classes, Methods, and Variables


• The concept is that whatever final is applied to
cannot be changed.
• Therefore:
– A final variable can never have its initial value
modified (i.e. it becomes a constant).
– A final method can never be over loaded.
– A final class can never be inherited from:
• Can never be a super class
• Can never have sub class descendants.
• Although the concept of a final class is unique
to Java, there are good conceptual reasons for
it:
– Points to Java for providing mechanisms for
restricting inheritance and overloading.
– Points against C++ for not making this process easy.

19
2/25/2009

Constants in Java

• Constants for a class should be public.


• Use the static and final declarations to ensure
that:
– the constant will always be available and
– the value of the constant can never be changed.
• Example:

public class TimeClass


{
private int hours, mins, secs,
elapsedmins, elapsedsecs;
public static final int MAXHOURS = 24;
public static final int MAXMINS = 60;
public static final int MAXSECS = 60;
...
}

Message Passing with Objects


• When passing objects in/out of a class
via accessors and mutators we have to
be careful about what we are doing.
• Remember that object variables (i.e.
non primitive) contain references not
values.
• We never want to pass a copy of a
reference outside of the object!
• We may want to pass a copy of the
information pointed to by the reference.

20
2/25/2009

Copying of Object Values

DateClass d1, d2, d3, d4;


d1=new DateClass(1,2,2000);
d2=new dateClass(3,3,2001);
d3 = d2;
d4 = new DateClass(d1);

Passing Out Objects


• Consider the two versions of the same mutator method
below:
public DateClass getDOB1()
{
return this.dob;
}
• This version is passing out a copy of the memory
address of the DateClass field dob (date of birth). This
means that the class calling this method can then
possibly modify the contents at the address. i.e. destroys
encapsulation.
public DateClass getDOB2()
{
return new DateClass( this.dob);
}
• This version passes the address of a complete copy of
the object and hence the class field name cannot be
modified outside the class.

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.

The equals() Method


• When comparing two objects we cannot simply use the
== operator.
if ( personOne == personTwo )
• The above if statement is comparing the memory
address stored in personOne with the memory address
stored in personTwo.
• What we really want to do is compare the data stored in
the objects which are located at each of the addresses.
• Every class in the standard Java library has a boolean
method called equals() which can be used to test the
equality of the data contained in two objects.
String name;
...
if ( name.equals("Slartibartfarst"))
• It is good programming practice to include an equals()
method in every class that you implement in Java
if ( personOne.equals(personTwo))

22
2/25/2009

DateClass equals() Method

public boolean equals( DateClass date)


{
return (( date.getDay() == day ) &&
( date.getMonth() == month ) &&
( date.getYear() == year ));
}

Hiding the Implementation


• A primary consideration in
object-oriented design is
"separating the things that
change from the things that stay
the same"
– The users of a library must be able
to rely on the part they use
• Must know they won't need to rewrite
code if a new version of the library is
released
– The library creator must have the
freedom to make modifications and
improvements

23
2/25/2009

Hiding the Implementation

• How can the library creator know


which data members have been
accessed by client programmers?
What if the library creator wants to rip
out an old implementation and put in
a new one?

Hiding the Implementation

• Java's access specifiers allow


the library creator to say what is
available to the client
programmer and what is not
• The client programmer is
"anyone who will be using my
class definitions"

24
2/25/2009

Hiding the Implementation

• The levels of access control from


“most access” to “least access” are
public, protected, package access
(which has no keyword), and private.
• Keep as “private” as possible, even
though it’s often counterintuitive for
people who program in other
languages (especially C) and are
used to accessing everything without
restriction, and expose only the
methods that you want the client
programmer to use.

Library

• The concept of a library and the


control over who can access the
library is not complete, however.
• There’s still the question of how they
are bundled together into a cohesive
library unit.
• This is controlled with the package
keyword in Java, and the access
specifiers are affected by whether a
class is in the same package or in a
separate package.

25
2/25/2009

Package : the Library Unit


• A package is what you get when
you use the import keyword to
bring in an entire library, as in
import java.util.*;
– Since class Vector is in package
java.util, this import lets you use
Vector in your program.
– You could also just use
"java.util.Vector" everywhere:
java.util.Vector v = new
java.util.Vector();

Package : the Library Unit

• The reason for importing is to


provide a mechanism to manage
"name spaces"
• The names of all your class
members are insulated from
each other
– A method f() inside a class A will
not clash with an f() with the same
signature in class B
• But what about the class
names?

26
2/25/2009

Package : the Library Unit

• Suppose you create a Stack


class and somebody else has
already created a Stack class?
– This can easily happen on the
Internet, as classes can get
downloaded automatically during
Java program execution
– The potential clashing of names is
why it's important to have
complete control over the name
space, and the ability to create a
unique name

Package : the Library Unit

• So far, most of our coding and


examples has been of a single class,
or two classes where no package
name was specified
– This means they're in the "default
package", the package with no name
• To save space, the examples will
mostly not have package statements
• Your code should always specify
package

27
2/25/2009

Package : the Library Unit

• Each class definition in Java is


created in a .java source file
• The Java compiler (javac.exe)
produces a .class file, which can then
be executed by running the Java VM
(java.exe)
• Java programs are typically
contained in a Java archive (.jar) file
– Simply a zipped bunch of class files, with
a little bit extra

Package : the Library Unit

• The names of .jar files have nothing


to do with the package names
– Of course, it's smart if the names are
meaningful!
• Package names have everything to
do with directory structure
– When you create a .zip file, you can
choose whether to preserve the path
– All .jar files do preserve the path!

28
2/25/2009

Package : the Library Unit

• The Java package directly represents


a directory hierarchy
• If my package name is "myPackage",
the Java interpreter (JVM) looks for
.class files in subdirectory
"myPackage"
• The classpath determines what
directories will be searched.
• The classpath can include .jar files as
well as ordinary directories

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

Package and Classpath

• When you specify a package in the


class definition, you are specifying
the directory structure in which the
compiled .class file will be stored
• Package names are subdirectory
names. The JVM will look in
directories specified in the
classpath for subdirectories
matching the package name.

30
2/25/2009

Exercise

• Create a program (or use an existing


program) but put it in package "test"
– Delete any old .class files of the name
you use
• Compile and run it.
– Did it work if you let the .class file be in
the StudentWork directory?
– What did you have to specify as compiler
options to get the right directory
structure?
– What did you have to specify to run it?

Creating Unique Package Names

• The standard for package names is


your domain name reversed
– "edu.cornell.cit.<application>" for me
– "com.ibm.<application>" for IBM
– "java." or "javax." for the Java
language
– "com.sun.java.<application>" for
other stuff from Sun
– What for you?

31
2/25/2009

Package names in .jar files

• Let's look again at a .jar file


using WinZip...
• .jar file names go in your
classpath as though they were
directories
-CLASSPATH .;.\JARS\jar1.jar
• The jar.exe utility preserves the
path in the .jar file it creates

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();

Using imports to change behavior

• You can create debugging versions


of classes and keep them in a
different package
– For example, System.out.println
statements in the methods
• For development, import the
debugging package
• When you're ready to move
forward, import the "real" package

33
2/25/2009

Package Caveat

• The package name specifies a


directory structure.
• The classes in a package must live in
the directory specified by the
package name
• This directory must be searchable
starting from the classpath
• Watch out for cascading
subdirectories!

Java Access Specifier

• Now that we know about packages,


the workings of the access modifiers
will be clearer
• The class definition controls access
to its own members.
– There's no way to "break in".
• The class may allow subclasses to
expose members.

34
2/25/2009

Java Access Specifier


• The levels of access control from
“most access” to “least access” are
public, protected, package access
(which has no keyword), and
private.
• From the previous slide you might
think that, as a library designer,
you’ll want to keep everything as
“private” as possible, and expose
only the methods that you want the
client programmer to use.

Friendly

• Default ("friendly") access is


"public to all other classes in my
package, but otherwise private"
• This is of dubious wisdom unless
you're absolutely certain that you
will always control all classes in
your package

35
2/25/2009

Public : Interface Access


• The members defined in the
interface (API) must be public
– They are what other programmers will
use
• Typical rule: only methods and
constants are public!
• Remember if you have additional
public members, you're extending
the interface
– Usually involves an iteration through
the design process

private: you can’t touch that!

• private access means "nothing


outside this class can see it"
• The programmer is free to modify
private members, as by definition
nobody can be using them
– Of course, the API must be preserved!
• Even constructors can be private!

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

protected: “sort of friendly”

• We haven't really discussed


inheritance in depth (although we
know that every object inherits from
Object)
• protected access is completely about
inheritance
• protected means "public to any
subclass of this class, private to any
other class"
• Remember that subclasses are
usually not in the same package

37
2/25/2009

Class Access

• Classes themselves have access


modifiers
– If you didn't specify one, it's friendly
– Default access is actually more useful for
a class than for its members
• Private classes are obviously of no
use, so you can't have them
• Ditto protected

Class Access

• If you can't see a class, you can't see


its members
– For a class with default access, its public
members are also accessible only within
the package
• If you can see the class, you can't
necessarily see its members
– Members can have more restrictive
access than the class they are part of

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

private boolean isvalidDate(int day,int


month,int year)
{
boolean validDate = false;
if (( year >= 1900 ) && ( year <= 2100 ))
if (( month >= 1 ) && ( month <= 12 ))
if ((day >=1)&&
(day<=daysInMonth(month,year)))
validDate = true;
return validDate;
}

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

private boolean isALeapyear( int year)


{
return (( year % 4 == 0 ) &&
(!(( year % 100 == 0 ) &&
( year % 400 != 0 ))));
}
} // end DateClass

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy