Is there a β€œnew” modifier for methods in Java?

Is there an equivalent C # new modifier in Java?

I would like to use it for unit tests - each init () method should be marked final and annotated with @Before. JUnit then executes all these init () methods.

I don’t want to worry about the new names for each of these init () methods, and I definitely want to mark them as final to make sure that they do not override each other (an alternative pattern is to override and call super.init () from each init method ()).

+2
source share
3 answers

A common template is to make your own "do" methods final and create protected (abstract) methods for subclasses.

In the superclass

 @Before public final void before() { onBefore(); } protected void onBefore() { } 

In subclass

 protected void onBefore() { // prepare the test fixture } 

It gives you the best of both worlds:

  • a well-known method of redefinition in subclasses;
  • redefinition is optional;
  • the superclass method is never overestimated;
  • the client method is called when the superclass makes a decision, that is, before or after the superclass makes a decision.

It has one drawback - it connects you with one superclass. However, this may not be a problem for your environment.

+5
source

Unfortunately not. Heck, before @Override there wasn’t even any way to protect against typos when overriding.

You cannot create a method with the same signature as the superclass method without overriding this method. Admittedly, I try not to do this even in C # ...

Have you considered using initFoo and initBar for the Foo and Bar classes, respectively (etc.)? This is a simple enough model to follow, and avoid name collisions. It seems a little ugly.

+2
source

Java has no equivalent to the C # new operator, which is

Used to hide an inherited element from an element of the base class.

What do you want to do, why not create a base class that your other tests can extend, and create an abstract method called init() (labeled @Before ) in the base class? This forces all subclasses to provide the init() method.

+1
source

All Articles