Java Reference
In-Depth Information
Any base class methods that are not specified in the derived class
are inherited unchanged, with the exception of the constructor. The
special case of the constructor is discussed in Section 4.1.6.
A derived class
inherits all data
members from the
base class and may
add more data
members.
n
Any base class method that is declared in the derived class's public
section is overridden. The new definition will be applied to objects of
the derived class.
n
The derived class
inherits all methods
from the base
class. It may accept
or redefine them.
It also can define
new methods.
Public base class methods may not be overridden in the private
section of the derived class, because that would be tantamount to
removing methods and would violate the IS-A relationship.
n
Additional methods can be added in the derived class.
n
4.1.2 type compatibility
The direct code reuse described in the preceding paragraph is a significant
gain. However, the more significant gain is indirect code reuse . This gain
comes from the fact that a Student IS-A Person and an Employee IS-A Person .
Because a Student IS-A Person , a Student object can be accessed by a
Person reference. The following code is thus legal:
Each derived class
is a completely new
class that nonethe-
less has some
compatibility with
the class from
which it was
derived.
Student s = new Student( "Joe", 26, "1 Main St",
"202-555-1212", 4.0 );
Person p = s;
System.out.println( "Age is " + p.getAge( ) );
This is legal because the static type (i.e., compile-time type) of p is Person .
Thus p may reference any object that IS-A Person , and any method that we
invoke through the p reference is guaranteed to make sense, since once a
method is defined for Person , it cannot be removed by a derived class.
You might ask why this is a big deal. The reason is that this applies not
only to assignment, but also to parameter passing. A method whose formal
parameter is a Person can receive anything that IS-A Person , including Student
and Employee .
So consider the following code written in any class :
public static boolean isOlder( Person p1, Person p2 )
{
return p1.getAge( ) > p2.getAge( );
}
Consider the following declarations, in which constructor arguments are
missing to save space:
Person p = new Person( ... );
Student s = new Student( ... );
Employee e = new Employee( ... );
 
Search WWH ::




Custom Search