Java Reference
In-Depth Information
viewpoint tells us that the inherited portion is a single entity, and the base
class constructor tells us how to initialize this single entity.
Base class constructors can be explicitly called by using the method super .
Thus the default constructor for a derived class is in reality
public Derived( )
{
super( );
}
The super method can be called with parameters that match a base class
constructor. As an example, Figure 4.7 illustrates the implementation of the
Student constructor.
The super method can be used only as the first line of a constructor. If it is
not provided, then an automatic call to super with no parameters is generated.
super is used to call
the base class con-
structor.
4.1.7 final methods and classes
As described earlier, the derived class either overrides or accepts the base
class methods. In many cases, it is clear that a particular base class method
should be invariant over the hierarchy, meaning that a derived class should not
override it. In this case, we can declare that the method is final and cannot be
overridden.
Declaring invariant methods final is not only good programming prac-
tice. It also can lead to more efficient code. It is good programming practice
because in addition to declaring your intentions to the reader of the program
and documentation, you prevent the accidental overriding of a method that
should not be overridden.
A final method is
invariant over the
inheritance hierar-
chy and may not be
overridden.
figure 4.7
A constructor for new
class Student ; uses
super
1 class Student extends Person
2 {
3 public Student( String n, int ag, String ad, String p,
4 double g )
5 { super( n, ag, ad, p ); gpa = g; }
6
7 // toString and getAge omitted
8
9 private double gpa;
10 }
 
Search WWH ::




Custom Search