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

前端 未结 4 931
鱼传尺愫
鱼传尺愫 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

    The way you've defined MyRelatedClass, you need to have an instance of MyClass to be able to access/instantiate this class.

    Typically in Java you use this pattern when an instance of MyRelatedClass needs to access some fields of a MyClass instance (hence the references to an "enclosing instance" in the compiler warning).

    Something like this should compile:

    public void doStuff() {
       MyClass mc = new MyClass();
       MyRelatedClass data = mc.new MyRelatedClass(); 
    }
    

    However, if a MyRelatedClass instance does not need access to fields of it's enclosing instance (MyClass's fields) then you should consider defining MyRelatedClass as a static class, this will allow the original code you've posted to compile.

    The difference in having a nested class (what you've posted) and a static nested class (a static class within a class) is that in the former, the nested class belongs to an instance of the parent class, while the latter has no such relationship - only a logical/namespace relationship.

提交回复
热议问题