Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an instance of inner class if the inner class is declared in the method of outer class?

I encounter the following question in Java, how to initialize an instance of inner class if the inner class is declared in the method of outer class? I met an compile error in the following case. Many thanks.

class Outer {
    public int a = 1;
    private int b = 2;
    public void method(final int c){
        int d = 3;
        class Inner{
            private void iMethod(int e){
                System.out.println("a = " + a);
                System.out.println("b = " + b);
                System.out.println("c = " + c);
                System.out.println("e = " + e);
            }
        }           
    }
    public static void main (String[] args){
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();// there is an compile error here
    }
}
like image 482
Huibin Zhang Avatar asked Oct 19 '13 20:10

Huibin Zhang


People also ask

How do you create an inner class instance from outside the outer class instance code?

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 outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.

Can you create an inner class inside a method?

Method-local Inner Class In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined.

When we create object of outer class the object of inner class is automatically created?

Rules for Inner ClassNo inner class objects are automatically instantiated with an outer class object. If the inner class is static, then the static inner class can be instantiated without an outer class instance. Otherwise, the inner class object must be associated with an instance of the outer class.

Can an inner class declared inside of a method access local variables of this method?

Yes, we can access the local final variables using the method local inner class because the final variables are stored on the heap and live as long as the method local inner class object may live.


Video Answer


1 Answers

how to initialize an instance of inner class if the inner class is declared in the method of outer class?

You can't. The scope of the class is confined to the method itself. It's similar to why you can't access local variables outside the method.

From JLS §6.3 - Scope of a Declaration:

The scope of a local class declaration immediately enclosed by a block (§14.2) is the rest of the immediately enclosing block, including its own class declaration.

like image 181
Rohit Jain Avatar answered Oct 19 '22 12:10

Rohit Jain