何时编写静态方法与实例方法的编码是否有经验法则? [英] Is there a rule of thumb for when to code a static method vs an instance method?

查看:131
本文介绍了何时编写静态方法与实例方法的编码是否有经验法则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java(和OOP),虽然它可能与我现在所处的位置无关,但我想知道是否可以分享一些常见的陷阱或良好的设计实践。

I'm learning Java (and OOP) and although it might irrelevant for where I'm at right now, I was wondering if SO could share some common pitfalls or good design practices.

推荐答案

要记住的一件重要事情是静态方法不能被子类覆盖。在代码中引用静态方法实际上将它与该实现联系起来。使用实例方法时,可以根据实例的类型改变行为。你可以利用多态性。静态方法更适合功能性类型的操作,其中行为是一成不变的。比如base 64编码或计算校验和。

One important thing to remember is that static methods cannot be overridden by a subclass. References to a static method in your code essentially tie it to that implementation. When using instance methods, behavior can be varied based on the type of the instance. You can take advantage of polymorphism. Static methods are more suited to utilitarian types of operations where the behavior is set in stone. Things like base 64 encoding or calculating a checksum for instance.

这篇关于何时编写静态方法与实例方法的编码是否有经验法则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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