是通过对象“坏形式”调用静态方法吗?为什么? [英] Is calling static methods via an object "bad form"? Why?

查看:181
本文介绍了是通过对象“坏形式”调用静态方法吗?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的一个问题中,有人询问静态方法,其中一个答案表明你通常会用以下内容称呼它们:

In a recent question, someone asked about static methods and one of the answers stated that you generally call them with something like:

MyClassName.myStaticMethod();

对此的评论还表明你也可以通过以下对象来调用它:

The comments on that also stated that you could also call it via an object with:

MyClassName myVar;
myVar.myStaticMethod();

但它被认为是不良形式。

but that it was considered bad form.

现在在我看来,这样做实际上可以让我的生活更轻松,所以我不必担心关于什么是静态的(a)

Now it seems to me that doing this can actually make my life easier so I don't have to worry about what's static or not (a).

通过对象调用静态函数有什么问题吗?显然你不想创建一个全新的对象只是为了调用它:

Is there some problem with calling static functions via an object? Obviously you wouldn't want to create a brand new object just to call it:

Integer xyzzy;
int plugh = xyzzy.parseInt ("42", 10);

但是,如果您已经拥有所需类型的对象,那么中是否存在问题使用吗?

But, if you already have an object of the desired type, is there a problem in using it?

(a)显然,我不能打电话一个非静态方法:

(a) Obviously, I can't call a non-static method with:

MyClassName.myNonStaticMethod();

但这不是我在这里问的问题。

but that's not the issue I'm asking about here.

推荐答案

错误的表单评论来自Java的编码约定

The bad form comment comes from the Coding Conventions for Java

参见 http://www.oracle.com/technetwork/java/codeconventions-137265.html#587

如果您考虑一下,它的原因是该方法是静态的,不会属于任何特定对象。因为它属于类,为什么要将特定对象提升到看似拥有方法的特殊状态?

The reason for it, if you think about it, is that the method, being static, does not belong to any particular object. Because it belongs to the class, why would you want to elevate a particular object to such a special status that it appears to own a method?

在您的特定示例中,您可以使用现有的整数来调用 parseInt (也就是说,它在Java中是合法的)但是这会让读者关注那个特定的整数宾语。它可能让读者感到困惑,因此指导就是避免这种风格。

In your particular example, you can use an existing integer through which to call parseInt (that is, it is legal in Java) but that puts the reader's focus on that particular integer object. It can be confusing to readers, and therefore the guidance is to avoid this style.

关于这使程序员的生活变得更轻松,转过身去问生活是什么阅读器更容易?有两种方法:实例和静态。当你看到表达式 Cm 并且你知道 C 是一个类时,你知道 m 必须是静态方法。当你看到 xm (其中 x 是一个实例)时你无法分辨,但它看起来像一个实例方法所以大多数人都只为实例方法保留这种语法。

Regarding this making life easier for you the programmer, turn it around and ask what makes life easier on the reader? There are two kinds of methods: instance and static. When you see a the expression C.m and you know C is a class, you know m must be a static method. When you see x.m (where x is an instance) you can't tell, but it looks like an instance method and so most everyone reserves this syntax for instance methods only.

这篇关于是通过对象“坏形式”调用静态方法吗?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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