Java Reference
In-Depth Information
Inheritance and Constructors
An object has two things: state and behavior. Instance variables in a class represent the state of its objects. Instance
methods represent the behavior of its objects. Each object of a class maintains its own state. When you create an
object of a class, memory is allocated for all instance variables declared in the class and all instance variables declared
in its ancestors at all levels. Your
Employee
class declares a
name
instance variable. When you create an object of the
Employee
class, the memory is allocated for its
name
instance variable. When an object of the
Manager
class is created,
memory is allocated for the
name
field that is present in its superclass
Employee
. After all, a manager has a similar state
as that of an employee. A manager behaves similar to an employee.
Let's look at an example. Consider two classes,
U
and
V
, as shown:
public class U {
private int id;
protected String name;
}
public class V extends U {
protected double salary;
protected String address;
}
Figure
16-3
depicts the memory allocation when objects of class
U
and
V
are created. When an object of class
U
is
created, memory is allocated only for the instance variables that are declared in class
U
. When an object of class
V
is
created, memory is allocated for all instance variables in class
U
and class
V
.
U u = new U( );
V v = new V( );
id
name
salary
address
id
name
Figure 16-3.
Memory allocation for an object includes all instance variable of the class and all its ancestors
Let's get to the main topic of discussion for this section, which is constructors. Constructors are not members
of a class and they are not inherited by subclasses. They are used to initialize instance variables. When you create an
object of a class, the object contains instance variables from the class and all of its ancestors. To initialize the instance
variables of ancestor classes, the constructors of ancestor classes must be called. Let's consider the following two
classes,
CSuper
and
CSub
, as shown in Listing 16-18 and Listing 16-19. The
CTest
class in Listing 16-20 is used to create
an object of the
CSub
class.