Java本地内部类中的访问方法 [英] Access methods within local inner classes in Java

查看:59
本文介绍了Java本地内部类中的访问方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以访问Java中的本地内部类的方法.以下代码是我之前尝试过的示例代码.因此,访问mInner()方法的机制是什么?

Is there any way to access the methods of local inner classes in Java. Following code is the sample code that I tried before. According to that what is the mechanism to access the mInner() method?

class Outer{
    int a=100;

    Object mOuter(){
        class Inner{
            void mInner(){
                int y=200;
                System.out.println("mInner..");
                System.out.println("y : "+y);
            }
        }
        Inner iob=new Inner();  
        return iob;
    }
}   
class Demo{
    public static void main(String args[]){
        Outer t=new Outer();
        Object ob=t.mOuter();
        ob.mInner(); // ?need a solution..
    }
}

推荐答案

正如ILikeTau的评论所说,您无法访问在方法中定义的类.您可以在方法之外定义它,但另一种可能性是定义interface(或抽象类).这样,代码仍将位于您的方法内部,并且可以访问该方法中定义的final变量和参数(如果将整个类移到外面,则无法执行此操作).像这样:

As ILikeTau's comment says, you can't access a class that you define in a method. You could define it outside the method, but another possibility is to define an interface (or abstract class). Then the code would still be inside your method, and could access final variables and parameters defined in the method (which you couldn't do if you moved the whole class outside). Something like:

class Outer {
    int a = 100;

    public interface AnInterface {
        void mInner();  // automatically "public"
    } 

    AnInterface mOuter() {   // note that the return type is no longer Object
        class Inner implements AnInterface {
            @Override
            public void mInner() {    // must be public
                int y = 200;
                System.out.println("mInner..");
                System.out.println("y : " + y);
            }
        }
        Inner iob = new Inner();  
        return iob;
    }
}   

class Demo {
    public static void main(String[] args) {  // the preferred syntax
        Outer t = new Outer();
        Outer.AnInterface ob = t.mOuter();
        ob.mInner(); 
    }
}

注意:未经测试

请注意,返回类型和ob的类型已从Object更改.这是因为在Java中,如果您声明某个内容为Object,则只能访问为Object定义的方法.编译器必须在编译时(而不是在运行时)知道您的对象ob具有mInner方法,并且无法知道它唯一知道的是Object.通过将其更改为AnInterface,编译器现在知道它具有mInner()方法.

Note that the return type, and the type of ob, have been changed from Object. That's because in Java, if you declare something to be an Object, you can only access the methods defined for Object. The compiler has to know, at compile time (not at run time) that your object ob has an mInner method, and it can't tell that if the only thing it knows is that it's an Object. By changing it to AnInterface, the compiler now knows that it has an mInner() method.

这篇关于Java本地内部类中的访问方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆