// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
class CallingCons {
public static void main(String args[]) {
C c = new C();
The output from this program is shown here:
Inside A's constructor
Inside B's constructor
Inside C's constructor
As you can see, the constructors are called in order of derivation.
If you think about it, it makes sense that constructors are executed in order of derivation.
Because a superclass has no knowledge of any subclass, any initialization it needs to perform
is separate from and possibly prerequisite to any initialization performed by the subclass.
Therefore, it must be executed first.
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as
a method in its superclass, then the method in the subclass is said to override the method in
the superclass. When an overridden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass. The version of the method defined
by the superclass will be hidden. Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks