In this demo we use the StartApplet3.java
starter, which includes a class called Test
and its subclass Test1,
which in turn is subclassed by Test2.
Each class includes two constructors. We use this()
and super()
to create different paths for the sequence of constructors invoked
in the building of the Test2
objects.
Two Test2
objects are created, each from a different starting constructor.
Each constructor prints out a message to indicate it was invoked.
Write down the sequence of messages before looking at the printout
to see if you understand how the sequence of constructors is built
up.
|
ConstructApplet.java
(Output goes to browser's Java
console.)
|
public
class ConstructApplet extends java.applet.Applet
{
public void init () {
System.out.println ("First test2
object");
Test2 test2 = new Test2 (1.2, 1.3);
System.out.println ();
System.out.println ("Second test2
object");
test2 = new Test2 (true, 1.2, 1.3);
}
// Paint message in Applet window.
public void paint (java.awt.Graphics g) {
g.drawString ("ConstructApplet",
10, 20);
}
}
/** Test is our base class. **/
class Test
{
int i;
double d;
boolean flag;
Test () {
d = 1.1;
flag = true;
System.out.println ("In Test ()");
}
Test (int j) {
this ();
i = j;
System.out.println ("In Test (int
j)");
}
}
/** Test 1 is a subclass of Test. **/
class Test1 extends Test
{
int k;
Test1 (boolean b) {
super (3);
flag = b;
System.out.println ("In Test1 (boolean
b)");
}
Test1 (boolean b, int j) {
this (b);
k = j;
System.out.println ("In Test1 (boolean
b, int j)");
}
}
/** And Test2 is a subclass of Test1. **/
class Test2 extends Test1
{
double x,y;
Test2 (double x, double y) {
super (false);
this.x = x;
this.y = y;
System.out.println ("In Test2 (double
x, double y)");
}
Test2 (boolean b, double x, double y) {
super (b,5);
flag = b;
System.out.println ("In Test2 (boolean
b, double x, double y)");
}
}
|
Latest Update: Oct. 21, 2004
|