In the demo belwo 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 a method. Because of inheritance, each of the
subclass also has the methods of its superclass(es). Each subclass
also inherits the data fields in its superclass(es)
Here we create an instance of each class and invoke the methods
available for that class.
|
InheritanceApplet.java
(Output goes to browser's Java
console.)
|
ublic
class InheritanceApp extends java.applet.Applet
{
public static void main (String args[]) {
// Create an instance of Test
Test test = new Test ();
// and invoke its only method.
test.aMethod ();
System.out.println ();
// Create an instance of Test1, which
extends Test
Test1 test1 = new Test1 ();
// Test1 inherits the aMethod from
Test and adds
// its own bMethod().
test1.aMethod ();
test1.bMethod ();
System.out.println ();
// Create an instance of Test2, which
extends Test1.
Test2 test2 = new Test2 ();
// Test2 inherits the aMethod from
Test, the bMethod from Test1,
// and adds its own cMethod().
test2.aMethod ();
test2.bMethod ();
test2.cMethod ();
}
}
/** Test is our base class. **/
class Test
{
int i = 5;
Test () {
System.out.println ("In Test object");
System.out.println ("
i = " + i);
}
void aMethod () {
System.out.println(" Called
aMethod()");
}
}
/** Test 1 is a subclass of Test. **/
class Test1 extends Test
{
int j = 10;
Test1 () {
System.out.println ("In Test1 object");
System.out.println ("
i = " + i);
System.out.println ("
j = " + j);
}
void bMethod () {
System.out.println(" Called
bMethod()");
}
}
/** And Test2 is a subclass of Test1. **/
class Test2 extends Test1
{
int k = 15;;
Test2 () {
System.out.println ("In Test2 object");
System.out.println ("
i = " + i);
System.out.println ("
j = " + j);
System.out.println ("
k = " + k);
}
void cMethod () {
System.out.println(" Called
cMethod()");
}
} |
|
The following shows the output from the above class:
In Test
object
i = 5
Called aMethod()
In Test object
i = 5
In Test1 object
i = 5
j = 10
Called aMethod()
Called bMethod()
In Test object
i = 5
In Test1 object
i = 5
j = 10
In Test2 object
i = 5
j = 10
k = 15
Called aMethod()
Called bMethod()
Called cMethod() |
We see that when we instantiate a subclass, the constructor(s)
of its superclass(es) are invoked first, starting from the lowest
base class.
Latest update: Oct. 21, 2004
|