Java Reference
In-Depth Information
The principle is simple: inheritance is an abstraction technique that lets us categorize classes of
objects under certain criteria and helps us specify the characteristics of these classes.
Exercise 8.3 Draw an inheritance hierarchy for the people in your place of study or work.
For example, if you are a university student, then your university probably has students (first-
year students, second-year students, . . .), professors, tutors, office personnel, etc.
8.4
Inheritance in Java
Before discussing more details of inheritance, we will have a look at how inheritance is ex-
pressed in the Java language. Here is a segment of the source code of the Post class:
public class Post
{
private String username; // username of the post's author
private long timestamp;
private int likes;
private ArrayList<String> comments;
// Constructors and methods omitted.
}
There is nothing special about this class so far. It starts with a normal class definition and de-
fines Post 's fields in the usual way. Next, we examine the source code of the MessagePost
class:
public class MessagePost extends Post
{
private String message;
// Constructors and methods omitted.
}
There are two things worth noting here. First, the keyword extends defines the inheritance re-
lationship. The phrase “ extends Post ” specifies that this class is a subclass of the Post class.
Second, the MessagePost class defines only those fields that are unique to MessagePost
objects (only message in this case). The fields from Post are inherited and do not need to be
listed here. Objects of class MessagePost will nonetheless have fields for username , time-
stamp , and so on.
Next, let us have a look at the source code of class PhotoPost :
public class PhotoPost extends Post
{
private String filename;
private String caption;
// Constructors and methods omitted.
}
This class follows the same pattern as the MessagePost class. It uses the extends keyword to
define itself as a subclass of Post and defines its own additional fields.
 
 
Search WWH ::




Custom Search