I have a final class, something like this:
public final class RainOnTrees{
public void startRain(){
// some code here
}
}
I
I guess you made it final
because you want to prevent other classes from extending RainOnTrees
. As Effective Java suggests (item 15), there's another way to keep a class close for extension without making it final
:
Remove the final
keyword;
Make its constructor private
. No class will be able to extend it because it won't be able to call the super
constructor;
Create a static factory method to instantiate your class.
// No more final keyword here.
public class RainOnTrees {
public static RainOnTrees newInstance() {
return new RainOnTrees();
}
private RainOnTrees() {
// Private constructor.
}
public void startRain() {
// some code here
}
}
By using this strategy, you'll be able to use Mockito and keep your class closed for extension with little boilerplate code.