gpt4 book ai didi

java - 我什么时候想让我的私有(private)类(class)成为静态的?

转载 作者:IT老高 更新时间:2023-10-28 20:24:33 25 4
gpt4 key购买 nike

一般来说,将私有(private)类声明为静态有什么好处?

在什么情况下我希望使用以下其中一种而不是另一种?

private static class Foo
{
...
}

private class Foo
{
...
}

最佳答案

我认为这是一个很好的起点: http://java67.blogspot.fi/2012/10/nested-class-java-static-vs-non-static-inner.html

1) Nested static class doesn't need reference of Outer class but non static nested class or Inner class requires Outer class reference. You can not create instance of Inner class without creating instance of Outer class. This is by far most important thing to consider while making a nested class static or non static.

2) static class is actually static member of class and can be used in static context e.g. static method or static block of Outer class.

3) Another difference between static and non static nested class is that you can not access non static members e.g. method and field into nested static class directly. If you do you will get error like "non static member can not be used in static context". While Inner class can access both static and non static member of Outer class.

关于java - 我什么时候想让我的私有(private)类(class)成为静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6223093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com