java 如何从静态 main() 方法调用内部类的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16954599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:30:52  来源:igfitidea点击:

how to call inner class's method from static main() method

javapolymorphisminner-classes

提问by sunny_dev

Trying to create 1 interface and 2 concrete classes inside a Parent class. This will qualify the enclosing classes to be Inner classes.

试图在父类中创建 1 个接口和 2 个具体类。这将使封闭类成为内部类。

public class Test2 {

       interface A{
             public void call();
       }

       class B implements A{
             public void call(){
                   System.out.println("inside class B");
             }
       }

       class C extends B implements A{
             public void call(){
                   super.call();
             }
       }


       public static void main(String[] args) {
              A a = new C();
              a.call();

       }
}

Now I am not really sure how to create the object of class C inside the static main() method and call class C's call() method. Right now I am getting problem in the line : A a = new C();

现在我不太确定如何在静态 main() 方法中创建类 C 的对象并调用类 C 的 call() 方法。现在我遇到了问题: A a = new C();

回答by Qiang Jin

Here the inner class is not static, so you need to create an instance of outer class and then invoke new,

这里的内部类不是静态的,所以需要先创建一个外部类的实例,然后再调用new,

A a = new Test2().new C();

But in this case, you can make the inner class static,

但是在这种情况下,您可以将内部类设为静态,

static class C extends B implements A

then it's ok to use,

然后就可以使用了

A a = new C()

回答by NINCOMPOOP

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

要实例化内部类,必须先实例化外部类。然后,使用以下语法在外部对象中创建内部对象:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

So you need to use :

所以你需要使用:

A a = new Test2().new C();

Refer the Java Tutorial.

请参阅Java 教程

回答by oks16

You should do this

你应该做这个

 A a = new Test2().new C();