Java Reference
In-Depth Information
Example 3.26 A class that implements an interface
class
Sample
implements Identifiable
{
private int id;
public void method()
{
System.out.println(id);
}
public int getID()
{
return id;
}
}
and assign an instance of the Sample class to it. In fact, you could assign an
instance of any class that implements the Identifiable interface to it.
Interfaces may also have an extends keyword. In other words, an interface
may inherit from an existing interface. This may be useful if you know you will
want to use methods from both the extended and the base interface without
having to cast the object reference. Otherwise extending an interface is
unnecessary since a given class may implement as many interfaces as desired.
3.4.2.1
Encapsulation and inheritance are related to one another and are controlled by
access modifiers on classes, data members, and methods. Let's spend a little time
talking about these modifiers and what they mean.
The access modifier keywords are public , private , and protected .
When a data member or method is private , it can only be accessed or called
from within this specific class. Neither classes that extend this class, nor classes
outside this class may access such a data member or call such a method. How-
ever, one instance of a class can access private members of another instance
of the same class. We don't encourage such use.
When a data member or method is marked protected , however, the only
classes that can access such a data member or method are either 1) classes that
extend this class and their descendants, or 2) other classes in this package (even
Inheritance and Encapsulation
Search WWH ::




Custom Search