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

查看:18
本文介绍了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天全站免登陆