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

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

    Yes, non static nested classes have access to the outer classes instance members, and therefore must be created for an instance of the outer class. So you have two choices:

    1. make the nested class static as Mervin suggests, or
    2. create it using an instance of the outer class as the error message suggests.

    In practice, I rarely create an instance of the inner class, except in methods of the outer class, and I rarely make such classes mutable -- but this is just me.

提交回复
热议问题