Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 10 of 10
class Point
{
private double x, y;
Point (double x, double y)
{
this.x = x;
this.y = y;
}
double getX ()
{
return x;
}
double getY ()
{
return y;
}
}
class Circle
{
private Point p;
private double radius;
Circle (double x, double y, double radius)
{
p = new Point (x, y);
this.radius = radius;
}
double getX ()
{
return p.getX ();
}
double getY ()
{
return p.getY ();
}
double getRadius ()
{
return radius;
}
}
From an external interface (not to be confused with the Java concept of interfaces) perspective, a Circle object created from this class is equivalent to an object created from the Circle class in this article's first code fragment. It would seem that it doesn't matter whether or not inheritance is used. But
it does: Take a good look at Circle. Notice the getX() and getY() methods. Those methods duplicate their counterparts in the Point class and do not promote code reuse. By focusing exclusively on composition and ignoring inheritance, you've added redundant
code to Circle. On a larger scale, this sort of redundant code could become a maintenance nightmare.
Objects have layers, and those layers result from inheritance. This article explored the object-oriented programming principle of inheritance and introduced you to single and multiple inheritance. You learned how to extend classes (which Java refers to as implementation inheritance), picked up some inheritance terminology, and examined those rules related to calling superclass constructors, overriding methods, and casting subclass object references to superclass references (and vice versa). Finally, you learned how inheritance and composition are related from an object-oriented design perspective.
Every subclass object is also a superclass object. What about those objects whose classes don't use extends to inherit capabilities from a superclass? Are such objects also subclass objects of some superclass? The answer is yes.
In the absence of extends, a class inherits from the root of all classes. And what class might that be? Tune in next month for the answer.