为什么java需要静态类_java – 为什么OOP中静态类的最佳实践有所不同?

我目前正在阅读有关

Java最佳实践的内容,我发现根据

this book,我们必须支持非静态的静态类.我记得在C#最佳实践中,我们必须根据Dennis Doomen的C#3.0,4.0和5.0编码指南来避免这种情况:

AV1008 – Avoid static classes

With the exception of extension method containers static classes very often lead to badly designed code. They are also very difficult,if not impossible,to test in isolation unless you’re willing to use some very hacky tools. Note If you really need that static class,mark it as static so that the compiler can prevent instance members and instantiating your class. This relieves you of creating an explicit private constructor.

我在C# answer和Java answer中找到了这两个用于避免静态类的时间,但仅仅是出于好奇 – C#和Java都是OOP语言,为什么它与最佳实践完全不同呢?

更新:

我不能从Java书中复制这么多页面,但底线是:

If you declare a member class that does not require access to an

enclosing

instance,always put the static modifier in its declaration,making it a static

rather than a nonstatic member class. If you omit this modifier,each instance will

have an extraneous reference to its enclosing instance. Storing this reference costs

time and space,and can result in the enclosing instance being retained when it

would otherwise be eligible for garbage collection (Item 6). And should you ever

need to allocate an instance without an enclosing instance,you’ll be unable to do

so,as nonstatic member class instances are required to have an enclosing instance.

A common use of private static member classes is to represent components of

the object represented by their enclosing class.

它只是关于性能吗?

请注意,这个问题更多的是关于静态类和OOP,而不是Java和C#之间的差异.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值