Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
This section discusses two techniques for writing code that can optionally use 1.1 API while remaining compatible with 1.0. If 1.0 compatibility isn't an issue for you, then skip this section.The first technique lets your program dynamically determine whether to invoke 1.0 or 1.1 API. The second technique lets you override deprecated methods without causing compiler warnings.
This technique consists of enclosing a 1.1 method invocation in atry
statement and putting alternative 1.0 code in the correspondingcatch
statement. Here's an example://Draw an unclosed polygon. try { g.drawPolyline(xPoints, yPoints, numPoints); //1.1 API } catch (NoSuchMethodError e) { g.drawPolygon(xPoints, yPoints, numPoints); //1.0 equivalent }
You might find yourself in the following situation:In this situation, you might wonder which version of the method you should override: the deprecated method or its replacement. If you simply override the replacement, then your code won't work correctly with 1.0 code that calls it. (If no 1.0 code will call the method, then this solution is fine.) If you simply override the deprecated version, then you'll see compilation warnings and you'll have 1.0 dependencies embedded in your code.
- You're writing 1.1-based code.
- It can be called by 1.0 code.
- You need to override a method that has been deprecated.
The solution is to override both methods. Override the deprecated method so that it calls the replacement method, and override the replacement method to provide the appropriate functionality. In your implementation of the deprecated method, use the
@deprecated
documentation tag to indicate that you are intentionally overriding the method to provide backwards compatibility. For example:This solution takes advantage of a loophole: The compiler doesn't warn you when you override a deprecated method and you mark the overriding method as deprecated. For example, the preceding code results in no warnings when compiled. However, if code that calls the preceding code is compiled, a deprecation warning occurs./** @deprecated */ public Dimension preferredSize() { return getPreferredSize(); } public Dimension getPreferredSize() { ...//implementation goes here }The solution described in this section helps you write code that is backwards compatible, compiles cleanly, and is easy to understand. When you no longer have to provide 1.0 compatibility, it'll be easy to find and remove the deprecated code.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.