关于java:我什么时候想让我的私有类静态?

When would I want to make my private class static?

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

在什么情况下,我想使用下面的一个而不是另一个?

1
2
3
4
private static class Foo
{
    ...
}

VS

1
2
3
4
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.


如果需要访问封闭类的成员变量/方法,请使用非静态形式。如果没有,请使用静态形式。


我假设你指的是内类。

我认为动机来自于你想如何将你的内心阶层联系起来。如果希望内部类与外部类的特定实例相关联,则使用private class,否则使用private static class


我发现在一般抽象类中有一个特定的异常非常有用。即。:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public abstract class AbstractClass <T>
{
    private void doSomethingOrThrowException() throws SpecificException
    {
        ....

        if ( ! successful)
        {
            throw new SpecificException();
        }
    }

    private static class SpecificException extends Exception {}
}

如果我不考虑静态的话,编译器会给我一个错误,说明:The generic class AbstractClass.SpecificException may not subclass java.lang.Throwable


静态类与普通类的区别仅仅在于它们可以在不创建实例的情况下被访问。因此,如果每次都需要一些类可访问,请使用static