可以使用对象实例访问Java中的静态方法 [英] Static method in Java can be accessed using object instance

查看:108
本文介绍了可以使用对象实例访问Java中的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,创建静态方法以在没有任何对象实例的情况下访问它。这对我来说很有意义。但最近我遇到一个奇怪的事情,Java中的静态方法也可以通过其对象实例访问。这对我来说非常奇怪。你们有谁知道为什么这个功能是由Java提供的?是什么意思允许静态方法被访问以及没有实例?

In Java static methods are created to access it without any object instance. It makes some sense to me. But recently I came across one strange thing that, static method in Java can also be accessed through its object instance. This looks pretty wierd to me. Does anyone of you know why this feature is provided by Java? Whats the significance of allowing static methods getting accessed with as well as without instance?

推荐答案

这样做的一个好处就是它可以让你获取实例方法并将其转换为静态方法,而无需修改任何现有代码(除了类),从而允许向后兼容。我发现这很有用,因为很多次我遇到了可以变为静态的实用程序方法 - 我可以添加 static 修饰符并继续我的方式。

A benefit of this is that it allows you to take an instance method and turn it into a static method without having to modify any existing code (other than the class) and thus allowing for backwards compatibility. I've found this useful as many times I've come across utility methods that can be made static - I can just add the static modifier and continue on my way.

这篇关于可以使用对象实例访问Java中的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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