转载

java – 如何从(静态)类中的类创建新的类实例?

我是 Java

新手(有C#经验),

这就是我想要做的:

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

public class OtherRandomClass
{
    public void DoStuff()
    {
       MyRelatedClass data = new MyClass.MyRelatedClass(); 
    }
}

这在Eclipse中给出了这个错误:

No enclosing instance of type BitmapEffects is accessible. Must qualify the allocation with an enclosing instance of type BitmapEffects (e.g. x.new A() where x is an instance of BitmapEffects).

这在C#中可以使用静态类,这里应该怎么做?

回应关于在一个文件中打包多个类的注释:与.NET不同,大多数java实现强制公共类类型的名称与声明类类型的文件名之间的严格关联.这不是一个硬性要求,但未使用未强制执行相关性的系统. JLS – 7.6 Top Level Type Declarations

说:

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).

看到这个问题: multiple class declarations in one file

如果您希望创建一个名称空间来包含相关的类,那么您需要使用静态内部类.静态声明并不意味着一个实例 – 它们仍然可以被实例化 – 静态意味着它们可以被实例化而无需引用封闭类.由于封闭类仅用于分组,而不是数据,因此您可以安全地将其设置为静态.为了更清楚地表明封闭类仅用于分组,您应该将其声明为接口,以便它不能被实例化并且没有实现细节.

虽然就个人而言,我不会这样做 – 在Java中,包用于强制执行命名空间.使用内部类很快就变得很麻烦. (我试过了!)

翻译自:https://stackoverflow.com/questions/3039306/how-can-i-create-a-new-class-instance-from-a-class-within-a-static-class

原文  https://codeday.me/bug/20190112/515183.html
正文到此结束
Loading...