Java Reference
In-Depth Information
Forcing certain behaviors on a class allows you to create more generic and
flexible classes that can communicate with completely different objects that
share a common interface. The MouseListener interface is an example of forc-
ing behavior on an object. When a mouse is clicked, a MouseEvent object is
instantiated and passed to a listener, invoking the mouseClicked() method.
How can the source of the MouseEvent know that a listener has even bothered
to write the mouseClicked() method? Because the listener was forced to imple-
ment the MouseListener interface, or it would not have been allowed to listen
for mouse clicks. Because the listener was forced to implement MouseListener,
the mouseClicked() method must have been written, so the source of the event
is guaranteed to be able to invoke mouseClicked() successfully on the listener.
Let's look at examples of both of these interface uses. We will start with a
class that uses an interface to expose certain methods in the class.
Exposing Methods via an Interface
The following code shows an Employee class that contains various methods
for accessing an employee's personal information, as well as methods for pay-
ing an employee. The details of the methods have been kept simple so as to not
to detract from the emphasis of this example.
public class Employee
{
private String name, address;
private double weeklyPay;
public Employee(String name, String address)
{
this.name = name;
this.address = address;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public String getAddress()
{
return address;
}
public void setAddress(String a)
{
address = a;
}
Search WWH ::




Custom Search