Java Reference
In-Depth Information
Similar to using this() in a constructor method, super() calls the constructor method
for the immediate superclass (which might, in turn, call the constructor of its superclass,
and so on). Note that a constructor with that signature has to exist in the superclass for
the call to super() to work. The Java compiler checks this when you try to compile the
source file.
You don't have to call the constructor in your superclass that has the same signature as
the constructor in your class; you have to call the constructor only for the values you
need initialized. In fact, you can create a class that has constructors with entirely differ-
ent signatures from any of the superclass's constructors.
Listing 5.8 shows a class called NamedPoint , which extends the class Point from the
java.awt package. The Point class has only one constructor, which takes an x and a y
argument and returns a Point object. NamedPoint has an additional instance variable (a
string for the name) and defines a constructor to initialize x , y , and the name.
LISTING 5.8
The NamedPoint Class
1: import java.awt.Point;
2:
3: class NamedPoint extends Point {
4: String name;
5:
6: NamedPoint(int x, int y, String name) {
7: super(x,y);
8: this.name = name;
9: }
10:
11: public static void main(String[] arguments) {
12: NamedPoint np = new NamedPoint(5, 5, “SmallPoint”);
13: System.out.println(“x is “ + np.x);
14: System.out.println(“y is “ + np.y);
15: System.out.println(“Name is “ + np.name);
16: }
17: }
5
The output of the program is as follows:
x is 5
y is 5
Name is SmallPoint
The constructor method defined here for NamedPoint calls Point 's constructor method
to initialize the instance variables of Point ( x and y ). Although you can just as easily
initialize x and y yourself, you might not know what other things Point is doing to
 
Search WWH ::




Custom Search