Java Reference
In-Depth Information
Code 9.1
continued
Source code of the
display methods
in all three classes
if (likes > 0) {
System.out.println( " — " + likes + " people like this." );
}
else {
System.out.println();
}
if (comments.isEmpty()) {
System.out.println( " No comments." );
}
else {
System.out.println( " " + comments.size() +
" comment(s). Click here to view." );
}
}
}
public class MessagePost extends Post
{
...
public void display()
{
System.out.println(message);
}
}
public class PhotoPost extends Post
{
...
public void display()
{
System.out.println( " [" + filename + "]" );
System.out.println( " " + caption);
Concept:
}
}
Overriding A
subclass can over-
ride a method
implementation.
To do this, the
subclass declares
a method with the
same signature
as the superclass,
but with a different
method body. The
overriding method
takes precedence
for method calls on
subclass objects.
This design works a bit better. It compiles, and it can be executed (even though it is not perfect
yet). An implementation of this design is provided in the project network-v3. (If you have done
Exercise 9.2, you already have a similar implementation of this design in your own version.)
The technique we are using here is called overriding (sometimes it is also referred to as redefini-
tion ). Overriding is a situation where a method is defined in a superclass (method display in class
Post in this example), and a method with exactly the same signature is defined in the subclass.
In this situation, objects of the subclass have two methods with the same name and header: one
inherited from the superclass and one from the subclass. Which one will be executed when we
call this method?
 
Search WWH ::




Custom Search