Java Function Annotation Help, use @Deprecated?
Deprecation means the method shouldn't be used any longer and that it may be removed in future releases. Basically exactly what you want.
Yes there's a trivially easy way to get a compile error when someone tries to use the method: Remove the method - that'll cause errors at linktime for any code that tries to use it, generally not to be recommended for obvious reasons, but if there's a really good reason to break backwards compatibility, that's the easiest way to achieve it. You could also make the method signature incompatible (always possible), but really the simplest solution that works is generally the best.
If you want a custom message when someone hovers over the method, use the javadoc for it, that's exactly what it's there for:
/**
* @deprecated
* explanation of why function was deprecated, if possible include what
* should be used.
*/
Generally, you use @Deprecated for methods that have been made obsolete by a newer version of your software, but which you're keeping around for API compatibility with code that depends on the old version. I'm not sure if it's exactly the best tag to use in this scenario, because getName is still being actively used by other subclasses of Animal
, but it will certainly alert users of the CatDog
class that they shouldn't call that method.
If you want to cause an error at compile time when that function is used, you can change your compiler options to consider use of @Deprecated methods to be an error instead of a warning. Of course, you can't guarantee that everyone who uses your library will set this option, and there's no way I know of to force a compile error just based on the language specification. Removing the method from CatDog
will still allow clients to call it, since the client will just be invoking the default implementation from the superclass Animal
(which presumably you still want to include that method).
It is certainly possible, however, to display a custom message when the user hovers over the deprecated method. The Javadoc @deprecated tag allows you to specify an explanation of why a method was deprecated, and it will pop up instead of the usual description of the method when the user hovers over the method in an IDE like Eclipse. It would look like this:
/**
*
* @deprecated Do not use this method!
*/
@Deprecated
public String getName() {
throw new UnsupportedOperationException();
}
(Note that you can make your implementation of the method throw an exception to guarantee that if the user didn't notice the @Deprecated tag at compile time, they'll definitely notice it at runtime).