将方法声明为静态的增益是多少 [英] What is the gain from declaring a method as static

查看:303
本文介绍了将方法声明为静态的增益是多少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在Eclipse中查看我的警告,遇到了这个问题:

I've recently been looking through my warnings in Eclipse and come across this one:

如果该方法可以声明为静态,它将给出编译器警告。

It will give a compiler warning if the method can be declared as static.

[edit] 在Eclipse帮助中精确引用,强调私人和最后:

[edit] Exact quote within the Eclipse help, with stress on private and final:


启用时,编译器会对
方法发出错误或警告,这些方法为私有最终,仅指静态$ b $

When enabled, the compiler will issue an error or a warning for methods which are private or final and which refer only to static members.

是的,我知道我可以关闭它,但我想知道启用它的原因吗?

Yes I know I can turn it off, but I want to know the reason for turning it on?

为什么会声明每种方法都可能是静态的?

这会带来任何性能好处吗? (在移动域中)

Will this give any performance benefits? (in a mobile domain)

指出一个方法是静态的,我想是显示你不使用任何实例变量,因此可以移动到utils风格类?

Pointing out a method as static, I suppose is showing that you don't use any instance variables therefore could be moved to a utils style class?

在一天结束时,我应该关闭忽略,还是应该修复它给我的100多条警告?

At the end of the day should I just turn this off 'ignore' or should I fix the 100+ warnings it has given me?

你认为这只是额外的脏的关键字,因为编译器只会引入这些方法吗? (类似你不声明每个变量你可以最终但你可以)。

Do you think this is just extra keywords that dirty the code, as the compiler will just inlines these methods anyway? (kind of like you don't declare every variable you can final but you could).

推荐答案

每当您编写方法时,您都会在给定范围内完成合同。

Whenever you write a method, you fulfill a contract in a given scope. The narrower the scope is, the smaller the chance is that you write a bug.

当一个方法是静态的,你不能访问非静态成员;因此,您的范围更窄。因此,如果您不需要 并且永远不需要(即使在子类中) 非静态成员来履行您的合同,为什么允许访问这些字段到您的方法?在这种情况下声明方法 static 将允许编译器检查您不使用您不打算使用的成员。

When a method is static, you can't access non-static members; hence, your scope is narrower. So, if you don't need and will never need (even in subclasses) non-static members to fulfill your contract, why give access to these fields to your method? Declaring the method static in this case will let the compiler check that you don't use members that you do not intend to use.

而且,它将帮助阅读你的代码的人理解合同的性质。

And moreover, it will help people reading your code understand the nature of the contract.

这就是为什么声明一个方法<$ c $

That's why it's considered good to declare a method static when it's actually implementing a static contract.

在某些情况下,你的方法只是一个相对于你的类的实例的东西,并且它的实现实际上不使用任何非静态字段或实例。在这种情况下,您不会标记方法 static

In some cases, your method only means something relative to an instance of your class, and it happens that its implementation doesn't actually use any non-static field or instance. In such cases, you would not mark the method static.

您不会使用 static 关键字:


  • 一个没有做任何事情的扩展钩子

  • 一个非常简单的默认行为意味着可以在子类中自定义。

  • 事件处理程序实现:事件处理程序,但不会使用事件处理程序实例的任何属性。

这篇关于将方法声明为静态的增益是多少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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