Here we give an example of method overloading. We use the starters
StartApp2.java
and StartApplet2.java,
which include the class Test
for inserting methods and data fields. In the main
routine, which is where the processing begins, we create an instance
of the Test
class and invoke its methods.
|
OverloadApplet.java
(Output goes to browser's Java
console.)
|
public
class OverloadApplet extends java.applet.Applet
{
public void init () {
//Create an instance of the Test
class
Test test = new Test ();
// Invoke all three overloaded
versions of aMethod
// in the class Test.
test.aMethod (3);
test.aMethod (4,5.6);
test.aMethod (7,8.9,true);
}
// Paint message in Applet window.
public void paint (java.awt.Graphics g) {
g.drawString ("OverloadApplet",
20, 20);
}
}
// The Test class holds three overloaded versions of aMethod().
class Test
{
int i = 0;
double x = 0.0;
boolean flag = false;
void aMethod (int j) {
i = j;
System.out.println ("In aMethod
(int j)");
System.out.println ("i = " + i);
System.out.println ("x = " + x);
System.out.println ("flag = " +
flag);
System.out.println ();
}
void aMethod (int j, double y) {
i = j;
x = y;
System.out.println ("In aMethod
(int j, double y)");
System.out.println ("i = " + i);
System.out.println ("x = " + x);
System.out.println ("flag = " +
flag);
System.out.println ();
}
void aMethod (int j, double y, boolean b) {
i = j;
x = y;
flag = b;
System.out.println ("In aMethod
(int j, double y, boolean b)");
System.out.println ("i = " + i);
System.out.println ("x = " + x);
System.out.println ("flag = " +
flag);
System.out.println ();
}
}
|
OverloadApp.java
- application version |
Latest update: Oct.19, 2004
|