How can I create a new class instance from a class within a (static) class?

前端 未结 4 930
鱼传尺愫
鱼传尺愫 2021-02-03 12:54

I\'m new to Java (have experience with C#),

this is what I want to do:

public final class MyClass
{
    public class MyRelatedClass
    {
      ...
    }         


        
4条回答
  •  孤独总比滥情好
    2021-02-03 13:42

    In response to the comments about packaging multiple classes in one file: unlike .NET, most implementations of java enforce a strict correlation between the name of public class type and the name of the file the class type is declared in. It's not a hard requirement, but not used a system where the correlation is not enforced. The JLS - 7.6 Top Level Type Declarations says this:

    When packages are stored in a file system (§7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

    • The type is referred to by code in other compilation units of the package in which the type is declared.
    • The type is declared public (and therefore is potentially accessible from code in other packages).

    See this SO question: multiple class declarations in one file

    If you are looking to create a namespace to enclose your related classes, then using static inner classes are what you need. The static declaration does not mean one instnace - they can still be instantiated - the static means that they can be instantiated without needing a reference to the enclosing class. As the enclosing class is just for grouping, and not data, you are safe making it a static. To make it clearer that the enclosing class is just for grouping, you should declare it as an interface, so that it cannot be instantiated and has no implementation details.

    Although personally, I would refrain from doing this - in Java, packages are used to enforce a namespace. Using inner classes for this quickly becomes cumbersome. (I have tried it!)

提交回复
热议问题