Say I have a library with an abstract class which has an abstract method:
public abstract class MyAbstractClass{
public void myMethod(){
int a = doSomething("hi");
}
public abstract void doSomething(String param);
}
Now I've decided to add a parameter to the method, but I want to keep the functionality of the old method to keep old code usable:
public void myMethod(){
int a = ?
}
/**
* @deprecated use doSomething(String, String) instead.
*/
@Deprecated
public int doSomething(String param){ return doSomething(param, null); }
public abstract int doSomething(String param, String secondParam);
How would I implement my myMethod in this scenario?
The PagerAdapter class in the Android support library has in fact some kind of construction like this, but the other way around:
public Object instantiateItem(ViewGroup container, int position) {
return instantiateItem((View) container, position);
}
/**
* @deprecated Use {@link #instantiateItem(ViewGroup, int)}
*/
public Object instantiateItem(View container, int position) {
throw new UnsupportedOperationException(
"Required method instantiateItem was not overridden");
}
Should this behavior be discouraged? And if I were to use this construction, how would I know what method to call?
I think I see your predicament. You have an abstract class in a library that people are subclassing and implementing it's abstract method and you want deprecate this method and add a new abstract method that moving forward should be implemented instead.
Here's what I would do:
Starting with a Feature class that users of your library are subclassing
public abstract class Feature {
public abstract void doSomething(String param);
}
Keep the Feature class pretty much as it is, however deprecate the method and advertise in your documentation that people should now subclass NewFeature instead of Feature and implement the shiny new abstract method in that class. Existing code that subclasses Feature should still work.
public abstract class Feature {
/**
@deprecated Extend NewFeature instead and implement doSomething(a, b)
*/
@Deprecated
public abstract void doSomething(String param);
}
public abstract class NewFeature extends Feature {
@Deprecated
@Override
public void doSomething(String param) {
doSomething(param, null);
}
public abstract void doSomething(String param, String paramTwo);
}
Once enough time has passed you could remove the Feature class. For example, I think spring tend to remove methods one whole version after they were first advertised as deprecated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With