If a developer extends a Java class that is part of the JDK and adds new methods to it, there is always the risk that a future version of java may introduce methods with the same name/signature resulting in unwanted behaviour if the program is executed with these future versions. Since there is no "Non-Overrides" annotation available (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7152222) which would detect such possible problems when someone compiles the code with a newer version of the JDK, the developer has to do this checks in a different way. Which approach do you use?
Asked
Active
Viewed 98 times
5
-
Which java class are u looking at extending? Maybe there is some advice on that if you can specify the use-case more. – vikingsteve Apr 29 '13 at 11:38
-
The problem occured during the transition from JDK6 to JDK7 where the getType() method was introduced in JDK7. We had some classes in our code extending java.awt.Window which already had a getType() method. – mschenk74 Apr 29 '13 at 12:39
2 Answers
13
It is an antipattern to extend JDK's classes, except those that are specifically designed to be used by extending them. You should use the Decorator pattern instead to add features to JDK classes. JDK is no special case, either, this holds for any 3rd party libraries as well.

Marko Topolnik
- 195,646
- 29
- 319
- 436
-
+1 - There is no future-proof way to extend classes that aren't designed to be extended. Best approach? Just don't do it at all! – Stephen C Apr 29 '13 at 11:36
-
The concrete JDK class was java.awt.Window, the concrete method was getType(). In general I would agree with you, but in this special case I think extending the Window class was the only possibility. – mschenk74 Apr 29 '13 at 12:33
-
@mschenk74 Since `Window` is the base of the complete GUI container class hierarchy, I don't see how you would be achieving anything even if you did subclass it: all the rest of the JDK would still continue to extend from `Window` and not from your custom subclass. – Marko Topolnik Apr 29 '13 at 12:35
-
Okay, my text was a bit to short: I meant: We subclassed one of the GUI classes (call it ClassX) that itself is a descendant of java.awt.Window. And then, the new method getType() in Window caused the problems. We didn't want to exchange the JDK Window class, we only wanted to be able to use our class in those places where ClassX is expected by the JDK. – mschenk74 Apr 29 '13 at 13:29
0
Inheritance is a powerful technique but due to lack of knowledge it can be worse. So In this case you have to use composition instead of inheritance. Create a class that contain the object of the any java class that you want to extend and then extend you class to that newly created class instead of the orignal class.

Waqas Ali
- 1,642
- 4
- 32
- 55