Is there an equivalent to C#'s new
modifier in Java?
I'd like to use it for unit tests - every init() method should be marked final and annotated with @Before. Then, jUnit executes all of these init() methods.
I don't want to bother coming up with new names for each of these init() methods, and I definitely wants to mark them as final to make sure they don't override eachother (an alternative pattern is to override and call super.init() from every init() method).
A common pattern is to make your own 'before' methods final and create protected (abstract) methods for the subclasses.
In the superclass
@Before
public final void before() {
onBefore();
}
protected void onBefore() {
}
In the subclass
protected void onBefore() {
// prepare the test fixture
}
This gives you the best of both worlds:
- a well-known method to override in sub-classes;
- overriding is optional;
- the superclass method is never overriden;
- the client method is invoked when the super-class decides, i.e. either before or after the super-class decides.
It does have a single downside - it ties you to a single super-class. Still, that may not be an issue to your environment.
Unfortunately not. Heck, before @Override
there wasn't even any way of protecting against typos when overriding.
You can't create a method with the same signature as a superclass method without it overriding that method. Admittedly I try not to do this even in C#...
Have you considered using initFoo
and initBar
for classes Foo
and Bar
respectively (etc)? It's a simple enough pattern to follow, and would avoid the name collisions. A bit ugly, admittedly.
Java does not have an equivalent to the C# new
operator which is
Used to hide an inherited member from a base class member.
For what you'd like to do, why not create a base class that your other tests can extend, and create an abstract
method named init()
(marked with @Before
) in the base class? This forces all subclasses to supply an init()
method.