声明一个最终的静态方法是一个坏主意吗? [英] Is it a bad idea to declare a final static method?

查看:33
本文介绍了声明一个最终的静态方法是一个坏主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白在这段代码中:

class Foo {
    public static void method() {
        System.out.println("in Foo");
    }
} 

class Bar extends Foo {
    public static void method() {
        System.out.println("in Bar");
    }
}

.. Bar 中的静态方法隐藏"了 Foo 中声明的静态方法,而不是在多态意义上覆盖它.

.. the static method in Bar 'hides' the static method declared in Foo, as opposed to overriding it in the polymorphism sense.

class Test {
    public static void main(String[] args) {
        Foo.method();
        Bar.method();
    }
}

...将输出:

在 Foo
在酒吧

in Foo
in Bar

Foo 中将 method() 重新定义为 final 将禁用 Bar 隐藏它的能力, 重新运行 main() 会输出:

Re-defining method() as final in Foo will disable the ability for Bar to hide it, and re-running main() will output:

在 Foo
在 Foo

in Foo
in Foo

(编辑:当你将方法标记为 final 时编译失败,只有当我删除 Bar.method() 时才会再次运行代码>)

(Edit: Compilation fails when you mark the method as final, and only runs again when I remove Bar.method())

将静态方法声明为 final 是否被认为是不好的做法,如果它阻止子类有意或无意地重新定义方法?

Is it considered bad practice to declare static methods as final, if it stops subclasses from intentionally or inadvertantly re-defining the method?

(this 很好地解释了使用 的行为最终是..)

(this is a good explanation of what the behaviour of using final is..)

推荐答案

我不认为将 static 方法标记为 final 是不好的做法.

I don't consider it's bad practice to mark a static method as final.

正如您所发现的,final 将防止该方法被子类隐藏这是个好消息,恕我直言.

As you found out, final will prevent the method from being hidden by subclasses which is very good news imho.

我对你的陈述感到非常惊讶:

I'm quite surprised by your statement:

在 Foo 中将 method() 重新定义为 final 将禁用 Bar 隐藏它的能力,并且重新运行 main() 将输出:

Re-defining method() as final in Foo will disable the ability for Bar to hide it, and re-running main() will output:

在Foo
在 Foo

in Foo
in Foo

不,在Foo 中将方法标记为final 将阻止Bar 编译.至少在 Eclipse 中我得到:

No, marking the method as final in Foo will prevent Bar from compiling. At least in Eclipse I'm getting:

线程main"中的异常java.lang.Error:未解决的编译问题:无法覆盖来自 Foo 的最终方法

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot override the final method from Foo

此外,我认为人们应该始终调用 static 方法,即使在类本身中也可以使用类名来限定它们:

Also, I think people should always invoke static method qualifying them with the class name even within the class itself:

class Foo
{
  private static final void foo()
  {
    System.out.println("hollywood!");
  }

  public Foo()
  {
    foo();      // both compile
    Foo.foo();  // but I prefer this one
  }
}

这篇关于声明一个最终的静态方法是一个坏主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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