java 为什么在类中有公共静态类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12077932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:30:47  来源:igfitidea点击:

Why have public static class inside a class

javanested-class

提问by noMAD

I was going through some code and I saw this:

我正在浏览一些代码,我看到了这个:

public class A {
    public A(SomeObject obj) {
      //Do something
    }
    //Some stuff
  public static class B {
    //Some other stuff
  }
}

I was wondering since even the inner class is publicwhy have it as nested and not a separate class? Also, can I do this here: new A.B(SomeObject)? I feel this defeats the purpose of a static class but I saw this implementation as well so wanted to know.

我想知道因为即使是内部类也是public为什么它是嵌套的而不是一个单独的类?另外,我可以在这里这样做new A.B(SomeObject)吗:?我觉得这违背了静态类的目的,但我也看到了这个实现,所以想知道。

回答by Jon Skeet

I was wondering since even the inner class is public why have it as nested and not a separate class?

我想知道即使内部类也是公共的,为什么要将它嵌套而不是单独的类?

That's really a matter to ask whoever wrote the class. It can allow the outer class to act as a "mini-namespace" though - if the nested class is onlyuseful in the context of the outer class, it seems reasonable. It indicates deliberate tight coupling between the two classes. I most often see this in the context of the builder pattern:

这真的是问谁写了这个类的问题。不过,它可以允许外部类充当“迷你命名空间”——如果嵌套类在外部类的上下文中有用,这似乎是合理的。它表明两个类之间故意紧密耦合。我最常在构建器模式的上下文中看到这一点:

Foo foo = new Foo.Builder().setBar(10).build();

Here it makes sense to me to have Foo.Buildernested within Foorather than as a peer class which would presumably be called FooBuilder.

在这里,Foo.Builder嵌套在其中Foo而不是作为可能被称为FooBuilder.

Note that it also gives some visibility differences compared with just unrelated classes.

请注意,与仅不相关的类相比,它还提供了一些可见性差异。

Also, can I do this here: new A.B(SomeObject)?

另外,我可以在这里这样做new A.B(SomeObject)吗:?

No, because Bdoesn't have a constructor with a SomeObjectparameter - only Adoes (in the example you've given).

不,因为B没有带SomeObject参数的构造函数 - 只有A(在你给出的例子中)。

I feel this defeats the purpose of a static class

我觉得这违背了静态类的目的

You should try to work out exactlywhat you deem the purpose of a static class to be, and in what way this defeats that purpose. Currently that's too vague a statement to be realistically discussed.

你应该尝试找出究竟是什么,你认为一个静态类的目的是,用什么方式这违背这一目的。目前,该声明过于模糊,无法进行实际讨论。

回答by Peter Lawrey

You would have an inner class like this so

你会有一个像这样的内部类

  • you can keep an class which only exists to support the outer class encapsulated.
  • you want to be able to access privatemembers of the outer class or other nested classes.
  • you want a nested class with static fields (a weak reason I know ;)
  • you have a class with a very generic name like Lockor Syncwhich you wouldn't want to be mixed with other classes of the same name used by classes in the same package.
  • 您可以保留一个仅存在于支持封装的外部类的类。
  • 您希望能够访问private外部类或其他嵌套类的成员。
  • 你想要一个带有静态字段的嵌套类(我知道这是一个薄弱的原因;)
  • 您有一个类的名称非常通用,Lock或者Sync您不希望将其与同一包中的类使用的其他同名类混合。

can I do this here: new A.B(SomeObject) ?

我可以在这里执行此操作:new AB(SomeObject) 吗?

You can.

你可以。

I feel this defeats the purpose of a static class

我觉得这违背了静态类的目的

It takes getting used to but once you start you may have trouble not turning your entire program into one file.java ;)

这需要习惯,但是一旦开始,您可能无法将整个程序转换为一个 file.java ;)

回答by Luke Taylor

I was wondering since even the inner class is public why have it as nested and not a separate class?

我想知道即使内部类也是公共的,为什么要将它嵌套而不是单独的类?

Have a look at this thread: Why strange naming convention of "AlertDialog.Builder" instead of "AlertDialogBuilder" in Android

看看这个线程:为什么在 Android 中使用“AlertDialog.Builder”而不是“AlertDialogBu​​ilder”的奇怪命名约定

Also, can I do this here: new A.B(SomeObject) ?

另外,我可以在这里执行此操作: new AB(SomeObject) 吗?

(Update)No, you can't do this, since B doesn't have a constructor that asks for SomeObject.

(更新)不,您不能这样做,因为 B 没有要求 SomeObject 的构造函数。

I hope this helps.

我希望这有帮助。

回答by Kumar Vivek Mitra

1.A static innerclass is known as Top-LevelClass.

1.一个static inner类被称为Top-Level类。

2.This static classhas direct accessto the Its Outer class Static method and variables.

2.static class可以直接访问其外部类的静态方法和变量。

3.You will need to initialize the static Inner classin this way from Outside...

3.您需要static Inner class从外部以这种方式初始化...

    A a = new A();
    A.B b = new A.B();

4.new A.B(SomeObject)won't work... because you don't have a constructorwith SomeObjectas parameter...

4.new A.B(SomeObject)不会工作......因为你没有SomeObject参数的构造函数......

5.But when the Inner class is Non-static, then it have implicit reference to the Outer class.

5.但是当Inner 类是Non-static 时,它就隐含了对Outer 类的引用。

6.The outer and inner class can extends to different classes.

6.外部类和内部类可以扩展到不同的类

7.An interface's methodcan be implemented more than oncein different or same ways, using Inner Class.

7.一种interface's method可以实现多于一次使用嵌套类在不同或相同的方式,。

回答by dcernahoschi

This pattern is used very often with the builder pattern. It not only makes clear the relation between a class and its builder, but also hides the ugly builder constructor/factory and makes builder more readable. For example in case you need your built object to have optional and not optional properties.

这种模式经常与建造者模式一起使用。它不仅明确了类与其构建器之间的关系,而且隐藏了丑陋的构建器构造函数/工厂,使构建器更具可读性。例如,如果您需要构建的对象具有可选而不是可选的属性。

public class AnObject {
   public static class AnObjectBuilder {

       private AnObject anObject;

       private AnObjectBuilder() {
       }

       private void newAnObjectWithMandatory(String someMandatoryField, ...) {
           anObject = new AnObject(someMandatoryField,...)
       }

       public AnObjectBuilder withSomeOptionalField(String opt) {
           ...
       }
   }

   public static AnObjectBuilder fooObject() {
        return (new AnObjectBuilder()).newAnObjectWithMandatory("foo")
   }

   public static AnObjectBuilder barObject() {
        return (new AnObjectBuilder()).newAnObjectWithMandatory("bar")
   }
}

This way the client code have to call first the static method on the AnObjectBuilderclass and then to use the optional builder methods:

这样,客户端代码必须首先调用AnObjectBuilder类上的静态方法,然后使用可选的构建器方法:

AnObject.fooObject("foo").withSomeOptionalField("xxx").build();without creating the builder object.

AnObject.fooObject("foo").withSomeOptionalField("xxx").build();无需创建构建器对象。

Pretty readable :)

相当可读:)

回答by Colin D

I was wondering since even the inner class is public why have it as nested and not a separate class?

我想知道即使内部类也是公共的,为什么要将它嵌套而不是单独的类?

The simple reason it is allowed is packaging convenience.

允许它的简单原因是包装方便。

Static nested class in Java, why?

Java中的静态嵌套类,为什么?

http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

yes, you can do new A.B(SomeObject). But you don't have to take my word for it, try it out.

是的,你可以做 new A.B(SomeObject)。但你不必相信我的话,试试看。