Java Reference
In-Depth Information
implementation of abstract data types. Like some other languages, such as C++, you
cannot separate the definition of a class from the definitions of its methods. If the user of a
class looks at the definition of the class, the user can also look at the definitions of the
methods. That is, implementation details of a class cannot be (directly) separated from
its specification details. In reality, the user of a class should only be concerned with the
specification, not the implementation. One way to accomplish this is to define an
interface that contains the methods headings and/or named constants. Then you can
define the class that implements the interface. The user can look at the interface and see
what operations are implemented by the class.
Just as you can create polymorphic references to classes in an inheritance hierarchy, you
can also create polymorphic references using interfaces. You can use an interface name as
the type of a reference variable, and the reference variable can point to any object of any
class that implements the interface. However, because an interface contains only method
headings and/or named constants, you cannot create an object of an interface.
Suppose that you have the following interface:
public interface Employee
{
public double wages();
public String department();
}
Now you declare a reference variable using the interface Employee . For example, the
following statement declares newEmployee to be a reference variable of type Employee :
Employee newEmployee;
However, the following statement is illegal because you cannot instantiate an object of an
interface :
newEmployee = new Employee(); //illegal
Suppose that you have two types of employees—part-time and full-time. You can define
the class FullTimeEmployee that implements the interface Employee . You can
use the reference variable newEmployee to create an object of the class
FullTimeEmployee . For example, the following statement creates an object of this class:
newEmployee = new FullTimeEmployee();
The following statement invokes the methods wages:
double salary = newEmployee.wages();
In a similar manner, if the class PartTimeEmployee implements the interface
Employee , the following statement creates an object of this class:
newEmployee = new PartTimeEmployee();
In addition to implementing methods of
1
0
the interface Employee ,
the class
FullTimeEmployee can contain additional methods. Suppose that
the class
FullTimeEmployee contains the method
Search WWH ::




Custom Search