permaculture playing cards*
The moose likes Java in General and the fly likes Inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Inheritance" Watch "Inheritance" New topic
Author

Inheritance

Keith Jones
Ranch Hand

Joined: Oct 30, 2006
Posts: 105
I was looking at the Properties class in Java and the comment said that as Properties inherits from Hashtable one could call put and putAll on a Properties object and that this was a problem because Properties should only contain Strings. This got me thinking. First I thought - what a lame idea inheriting from a class when not all the features of the parent class apply to the child. Then I thought wouldn't it be a great idea to have a parent-child relationship where the child can "turn off" certain features of the parent. So in this case Properties could turn off put and putAll of HashTable. But of course this would cause no end of problems:

HashTable h = new Properties();
h.putAll(); // turned off

Anyway, just thought I'd share my thoughts. I wonder if there are any languages that allow turning off of features like this?


SCJP 1.4
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Removing some of the members would violate the Liskov Substitution Principle; this is one of the cornerstones of the concept of polymorphism. The linked article is a little formal; in essence, the LSP says that anything you can do to a parent object, you can do to a child. If the LSP is violated, then all sorts of things don't work right. In the case of what you're describing, you'd end up with lots of "NoSuchMethodException"s at runtime.

C++ has "private inheritance", in which the public members of the parent aren't exposed on the child; the child can call them, but clients of the child are not. This doesn't violate the LSP because the parent type isn't inherited, either: a child is-not-a parent in this case.

What you can do, and what the author of Properties should have done (and the author of java.util.Stack, and you can find lots of other examples in the Java APIs) is use delegation. Instead of extending Hashtable, Properties should have held a Hashtable member, and then implemented methods like



[Jess in Action][AskingGoodQuestions]
Keith Jones
Ranch Hand

Joined: Oct 30, 2006
Posts: 105
well put.
 
GeeCON Prague 2014
 
subject: Inheritance