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
Discover Code::Blocks, an open source IDE for C/C++.
Explore the basics of accessing a Twitter account and look at the ways we can search and interact with the data available to you.
Learn how to create a little Instagram app with Visual Basic.
Arun Karthick introduces you to the state machine model and shows you how to create a simple working state machine sample using the .NET framework in the C# language.