Java中的方法是否有'new'修饰符? [英] Is there a 'new' modifier for methods in Java?

查看:161
本文介绍了Java中的方法是否有'new'修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有相当于 C#的< Java中的code> new 修饰符?

Is there an equivalent to C#'s new modifier in Java?

我想将它用于单元测试 - 每个init( )方法应标记为final并用@Before注释。然后,jUnit执行所有这些init()方法。

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.

我不想打扰每个init()方法的新名称,我肯定希望将它们标记为final以确保它们不会覆盖彼此(另一种模式是覆盖并从每个init()方法调用super.init())。

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).

推荐答案

一种常见的模式是让你自己的'before'方法最终,并为子类创建受保护的(抽象)方法。

A common pattern is to make your own 'before' methods final and create protected (abstract) methods for the subclasses.

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

protected void onBefore()  {

}



在子类中



In the subclass

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

这为您提供两全其美:


  • 在子类中重写的众所周知的方法;

  • 覆盖是可选的;

  • 超类方法永远不会被覆盖;

  • 当超类决定时, ie 在超类决定之前或之后调用客户端方法。

  • 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.

这篇关于Java中的方法是否有'new'修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆