Java Reference
In-Depth Information
Listing 16-7.
An EarlyBindingSub Class, Which Inherits from EarlyBindingSuper Class and Has a Static Field,
an Instance Field, and a Static Method, Which Are of the Same Type as in Its Superclass
// EarlyBindingSub.java
package com.jdojo.inheritance;
public class EarlyBindingSub extends EarlyBindingSuper{
// An instance variable
public String str = "EarlyBindingSub";
// A static variable
public static int count = 200;
public static void print() {
System.out.println("Inside EarlyBindingSub.print()");
}
}
The
EarlyBindingSuper
class declares two fields:
str
and
count
. The
str
field is declared non-static and
count
is
declared
static
. The
print()
method is declared
static
.
The
EarlyBindingSub
class inherits from the
EarlyBindingSuper
class and it declares the same types of fields
and methods, which have the same names. Fields are set to different values and the method prints a different
message in the
EarlyBindingSub
class, so you can know which one is accessed when you execute your code. The
EarlyBindingTest
class in Listing 16-8 demonstrates the result of the early binding.
Listing 16-8.
A Test Class to Demonstrate Early Binding for Fields and Methods
// EarlyBindingTest.java
package com.jdojo.inheritance;
public class EarlyBindingTest {
public static void main(String[] args) {
EarlyBindingSuper ebSuper = new EarlyBindingSuper();
EarlyBindingSub ebSub = new EarlyBindingSub();
// Will access EarlyBindingSuper.str
System.out.println(ebSuper.str);
// Will access EarlyBindingSuper.count
System.out.println(ebSuper.count);
// Will access EarlyBindingSuper.print()
ebSuper.print();
System.out.println("------------------------------");
// Will access EarlyBindingSub.str
System.out.println(ebSub.str);
// Will access EarlyBindingSub.count
System.out.println(ebSub.count);