Java Reference
In-Depth Information
a design decision. Depending on the circumstances, one or the other will likely be
the more natural choice.
A word about System.out.println()
We've frequently encountered the method System.out.println() —it's used to dis‐
play output to the terminal window or console. We've never explained why this
method has such a long, awkward name or what those two periods are doing in it.
Now that you understand class and instance fields and class and instance methods,
it is easier to understand what is going on: System is a class. It has a public class field
named out . This field is an object of type java.io.PrintStream , and it has an
instance method named println() .
We can use static imports to make this a bit shorter with import static
java.lang.System.out; —this will enable us to refer to the printing method as
out.println() but as this is an instance method, we cannot shorten it any further.
Composition Versus Inheritance
Inheritance is not the only technique at our disposal in object-oriented design.
Objects can contain references to other objects, so a larger conceptual unit can be
aggregated out of smaller component parts—this is known as composition . One
important related technique is delegation , where an object of a particular type holds
a reference to a secondary object of a compatible type, and forwards all operations
to the secondary object. This is frequently done using interface types, as shown in
this example where we model the employment structure of software companies:
O n
public interface Employee {
void work ();
}
public class Programmer implements Employee {
public void work () { /* program computer */ }
}
public class Manager implements Employee {
private Employee report ;
public Manager ( Employee staff ) {
report = staff ;
}
public Employee setReport ( Employee staff ) {
report = staff ;
}
public void work () {
report . work ();
}
}
Search WWH ::




Custom Search