0
package collections; 
public class Construct 
  { 
    class Inner
      { 
        void inner() 
          { 
            System.out.println("inner class method "); 
          } 
      } 
    public static void main(String[] args) 
      { 
        Construct c=new Construct(); 
      } 
  } 

How to call a method of the inner class? How to create an object to call a method of the inner class?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140

3 Answers3

2

Use this:

Inner inner = new Construct().new Inner();
inner.inner();
sarkasronie
  • 335
  • 1
  • 2
  • 15
0

Inner class is a nested class. Nested classes can be static or not. If static then its called static nested class and if not its called inner classes.

Non-static nested classes hold a reference to the Outer class that they are nested within.

What you have is an inner nested class, so we need to instantiate the inner class with a reference from the Outer like so:

Construct c = new Construct();
Inner inner = c.new Inner(); //using reference to create inner
inner.inner(); //Calling method from inner.
dovetalk
  • 1,995
  • 1
  • 13
  • 21
0

Depends upon whether your class is static or non-static.

For non-static inner class, use this:

Inner inner = new Construct().new Inner();
inner.inner()

For static inner-class, use this:

InnerStatic inner = new Construct.Inner();
inner.inner()