Now let's sub-class it to be a 3D point:.
#Notes
Josh Bloch's "Effective Java" Item 8 was the source of this example, but Bloch uses a ColorPoint which adds a color instead of a third axis and uses doubles instead of ints. Bloch's Java example is basically duplicated by Odersky/Spoon/Venners who made their example available online.
Josh Bloch's "Effective Java" Item 8 was the source of this example, but Bloch uses a ColorPoint which adds a color instead of a third axis and uses doubles instead of ints. Bloch's Java example is basically duplicated by Odersky/Spoon/Venners who made their example available online.
Several people have objected to this example because if you let the parent class know about the sub-class, you can fix this issue. That's true if there are a small enough number of sub-classes and if the parent knows about them all. But the original question was about making an API which someone else will write sub-classes for. In that case, you generally can't update the parent implementation to be compatible with the sub-classes.