简体   繁体   English

如何从外部类的主方法调用异常类的方法

[英]how to invoke method of annoymous class from the main method of the outer class

I'm new to Java and is trying to learn the concept of anonymous class. 我是Java的新手,正在尝试学习匿名类的概念。 Could someone please tell me how I can invoke the 'awesomeMethod' from the main method of the LocallClassExample? 有人可以告诉我如何从LocallClassExample的主方法中调用“ awesomeMethod”吗?

public class LocalClassExample {

    interface Awesome {

        public void awesomeMethod();
    }

    class AwesomeClass {

        public int finalInt= 10;

        Awesome a1 = new Awesome() {

            @Override
            public void awesomeMethod() {
                System.out.println(finalInt);
            }
        };
    }

    public static void main(String[] args) {        

    }
}

Consider this: 考虑一下:

new AwesomeClass().a1.awesomeMethod();

will invoke the method awesomeMethod() on the member variable a1 (which is something Awesome ) of the newly created instance of AwesomeClass . 将在新创建的AwesomeClass实例的成员变量a1 (这是Awesome awesomeMethod()上调用方法awesomeMethod()

It will get more tricky once your main is outside of your AwesomeClass - and more so once it's outside of the package. 一旦您的main在AwesomeClass之外,它将变得更加棘手-在main之外的情况下,它将变得更加棘手。 In these cases you'd have to provide a getter like 在这种情况下,您必须提供类似

public Awesome getAwesome() { 
  return a1; 
}

Which would when invoked still execute the method as defined in your anonymous class. 当调用时,哪种方法仍将执行匿名类中定义的方法。

Try to use this to create inner class object as: 尝试使用它来创建内部类对象,如下所示:

  public static void main(String[] args) {        
    LocalClassExample.AwesomeClass oi = new LocalClassExample().new AwesomeClass();
  oi.awesomeMethod();
}

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

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