What approach to use in own programs to leverage updates to future java versions?
Asked Answered
K

2

5

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 https://bugs.java.com/bugdatabase/view_bug?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?

Kaitlinkaitlyn answered 29/4, 2013 at 11:30 Comment(2)
Which java class are u looking at extending? Maybe there is some advice on that if you can specify the use-case more.Perplexed
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.Kaitlinkaitlyn
E
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.

Eldreda answered 29/4, 2013 at 11:32 Comment(4)
+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!Waksman
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.Kaitlinkaitlyn
@Kaitlinkaitlyn 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.Eldreda
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.Kaitlinkaitlyn
C
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.

Concert answered 29/4, 2013 at 11:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.