Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access methods within local inner classes in Java

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..
    }
}
like image 329
Saveendra Ekanayake Avatar asked Sep 05 '15 03:09

Saveendra Ekanayake


1 Answers

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(); 
    }
}

Note: not tested

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.

like image 88
ajb Avatar answered Oct 05 '22 00:10

ajb