为什么最好在方法类的实例中静态调用静态方法? [英] Why is it preferable to call a static method statically from within an instance of the method's class?

查看:110
本文介绍了为什么最好在方法类的实例中静态调用静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Java中创建一个类的实例,为什么最好静态地调用同一个类的静态方法,而不是使用this.method()?

If I create an instance of a class in Java, why is it preferable to call a static method of that same class statically, rather than using this.method()?

当我尝试通过this.staticMethod()从自定义类的构造函数中调用静态方法staticMethod()时,我收到来自Eclipse的警告。

I get a warning from Eclipse when I try to call static method staticMethod() from within the custom class's constructor via this.staticMethod().

public MyClass() { this.staticMethod(); }

vs

public MyClass() { MyClass.staticMethod(); }

任何人都可以解释为什么这是一件坏事吗?在我看来,编译器应该已经分配了对象的实例,因此静态分配内存将不需要开销。

Can anyone explain why this is a bad thing to do? It seems to me like the compiler should already have allocated an instance of the object, so statically allocating memory would be unneeded overhead.

编辑:

我听到的要点是,这是不好的做法,主要是因为可读性,这是可以理解的。我真正想要问的是(尽管不是很清楚)在调用MyClass.staticMethod()或this.staticMethod()之间的'编译'有什么不同之处。

The gist of what I'm hearing is that this is bad practice mainly because of readability, and understandably so. What I was really trying to ask (albeit not very clearly) was what differences there are at 'compilation', if any, between calling MyClass.staticMethod() or this.staticMethod().

推荐答案

MyClass.staticMethod()清楚地表明您正在调用静态(不可重写)方法。

MyClass.staticMethod() makes it clear that you are calling a static (non-overrideable) method.

this.staticMethod()误导读者认为它是一个实例方法。

this.staticMethod() misleads the reader into thinking that it is an instance method.

staticMethod()也在误导方面(虽然我通常这样做)。

staticMethod() is also on the misleading side (though I normally do it that way).

如果你认为人们在阅读你不熟悉的代码时会倾向于使代码更清晰,这就是代码更清晰的情况。有ClassName.method而不是instance.method。

If you think of people reading your code as unfamiliar with it you tend to try to make the code clearer, and this is a case where the code is clearer by having ClassName.method instead of instance.method.

这篇关于为什么最好在方法类的实例中静态调用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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