简体   繁体   English

抽象类实例化内部类

[英]Abstract class instantiating inner class

I have an abstract class with a non-static non abstract inner class that I have to instantiate from a static method.我有一个带有非静态非抽象内部类的抽象类,我必须从静态方法实例化它。 how can this be done?如何才能做到这一点?

This is basically what I am trying to do:这基本上就是我想要做的:

abstract class Program
{
    private static Window window;

    public static void main(String[] args)
    {
        Program program = new Program();
        window = program.new Window();
    }

    abstract void Update();

    class Window
    {
        public Window()
        {
            //some code
        }

        public void someMethod()
        {
            Update();
        }
    }
}

I know you cannot instantiate an abstract class, and you can't instantiate the inner class from a static method without an instance of the outer class, so I have no idea what to do.我知道你不能实例化一个抽象类,你不能在没有外部类实例的情况下从静态方法实例化内部类,所以我不知道该怎么做。

What you can do is just create one class which extends your abstract class and in that class you can instantiate your inner class like following:您可以做的只是创建一个扩展抽象类的类,在该类中您可以实例化您的内部类,如下所示:

public class TestProgram extends Program
 {

  public static void main(String[] args)
   {
    Program program = new TestProgram();
    Window window = program.new Window();
  }
}

The simplest answer seems to be create an implementation of Program that you can use to instantiate Window objects from.最简单的答案似乎是创建一个 Program 实现,您可以使用它来实例化 Window 对象。

More generally, I think your paradox is your answer.更一般地说,我认为你的悖论就是你的答案。 You're trying to design something that won't work within the language constraints and you'll have to give up the abstract nature of Program or make Window a class you can create outside of a Program.您正在尝试设计一些在语言限制内不起作用的东西,您将不得不放弃 Program 的抽象性质或使 Window 成为您可以在 Program 之外创建的类。

Why do you have your main method inside of an abstract class ?为什么在abstract class有 main 方法?

The bigger problem here is the design.这里更大的问题是设计。 What is the point of having that Window class an inner class?将该 Window 类作为内部类有什么意义? If you want to instantiate that object from within the abstract class, just make Window it's own top level class.如果您想从抽象类中实例化该对象,只需将 Window 设为自己的顶级类。

It doesnt appear to access anything from its containing class, so why have it be an inner class?它似乎没有从它的包含类访问任何东西,那么为什么它是一个内部类呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM