One of the most compelling features about Java is code reuse . But to be revolutionary, you’ve got to be able to do a lot more than copy code and change it.
Latest Thinking In Java Articles - Page 5
It is very common to use composition and inheritance together. The following example shows the creation of a more complex class, using both inheritance and composition, along with the necessary constructor initialization:
Inheritance is such an integral part of Java (and OOP languages in general) that it was introduced in Chapter 1 and has been used occasionally in chapters before this one because certain situations required it. In addition, you’re always doing inheritance when you create a class, because if you don’t say otherwise you inherit from Java’s standard root class Object .
Now that you’ve been introduced to inheritance, the keyword protected finally has meaning. In an ideal world, private members would always be hard-and-fast private , but in real projects there are times when you want to make something hidden from the world at large and yet allow access for members of derived classes. The protected keyword is a nod to pragmatism. It says “This is private as far as the class user is concerned, but available to anyone who inherits from this class or anyone else in the same package .” That is, protected in Java is automatically “friendly.”
Both inheritance and composition allow you to create a new type from existing types. Typically, however, you use composition to reuse existing types as part of the underlying implementation of the new type and inheritance when you want to reuse the interface. Since the derived class has the base-class interface, it can be upcast to the base, which is critical for polymorphism, as you’ll see in the next chapter.
The most important aspect of inheritance is not that it provides methods for the new class. It’s the relationship expressed between the new class and the base class. This relationship can be summarized by saying “The new class is a type of the existing class.”
Latest Developer VideosMore...
Latest CodeGuru Developer Columns
It's essential to know the differences in these libraries and use them correctly. This brief tutorial will guide you.
With facilities to search, copy, extract segments, and more, the array class can handle pretty much any task you need to perform with ease.
Enhance your development skills and make your users' lives easier.
If you have written solid code, you have accomplished one half of the objective. Solid code is the protagonist, or hero, of our story, but testing is the more sedate side kick that often saves the day after the hubris of the hero has almost certainly lead to calamity.