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

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

问题描述

在最近的一个问题中,有人询问了静态方法,其中一个答案表示您通常使用以下内容调用它们:

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.

关于这让程序员的生活更轻松,请转过头来问问是什么让读者的生活更轻松?有两种方法:实例和静态.当您看到表达式 C.m 并且您知道 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天全站免登陆