Java Reference
In-Depth Information
public class Group implements Component {
@Override
public void method1() {/*...*/}
@Override
public void method2() {/*...*/}
public void addMember(Member member) {/*...*/}
public void removeMember(Member member) {/*...*/}
public Member getMember(int i) {/*...*/}
public int nrMembers() {/*...*/}
// Other methods
}
This implementation can be useful when the member and group nodes do not share any behavior
other than a particular set of methods defined in the interface, or when you explicitly want to pre-
vent executing list methods ( addMember , removeMember ... ) on the member objects. Note that it is
also possible to combine the two approaches by defining an interface, an abstract class that imple-
ments the interface, and subclasses.
the interface‐abstract combo
This is a good point in the chapter to mention a particularly curious pattern that
you might see in large, heavily “architected” codebases: the combination of an
abstract class and an interface.
These classes will often be scattered across different packages, so you need to go on
a hunt to find the code you're looking for in the dependency tree. For instance, an
interface class might be named IPerson , PersonInterface , or just Person , and be
located in the com.bigcompany.models.hr package, or perhaps in com.bigcom-
pany.models.hr.interface . The abstract class implementing this interface might
be named AbstractPerson , PersonImpl , PersonImplementation , or Person , and
be located in com.bigcompany.models.hr or com.bigcompany.models.hr.impl ,
perhaps. The subclasses extending the abstract class are then named NormalPerson
and VIPPerson , or NormalPersonImpl and VIPPersonImpl , and are located in
com.bigcompany.models.hr or com.bigcompany.models.hr.impl . . .
What is going on here? In terms of, naming, different programmers prefer different
strategies, but in general, an interface defines a contract that the implementations
should adhere to. This immediately provides a good heuristic for deciding between
an interface and an abstract class: a person is a noun. Normal persons and VIP per-
sons are always, by definition, people. Starting with an abstract class makes more
sense in this case. An abstract class describes all the subclasses.
The interface describes what the implementing classes should be able to do .
Consider the Comparable built‐in interface in Java, which describes the implemen-
tations that should add a method that allows you to compare one object of the
implementing class to another object of that class. Maybe this applies to all persons
 
Search WWH ::




Custom Search