Search code examples
javaoopinterfaceinner-classes

How can I access inner class methods directly from other class in Java?


I have implemented two intefaces like this:

public OuterClass implements Interface1 {

    public InnerClass implements Interface2 {

    }
} 

How can I access inner class methods directly from other classes in Java? Is it allowed in Java?


Solution

  • When you define a method in InnerClass, you need to have an instance of InnerClass to call a (non-static) method on it. So we add a simple method to your example...

    public class OuterClass implements Interface1 {
        
        public class InnerClass implements Interface2 {
            
            public void method() {
                System.out.println("hello");
            }
        }
    }
    

    ... create an instance of InnerClass and call the method like this:

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        OuterClass.InnerClass inner = outer.new InnerClass();
        inner.method();
    }
    // output: hello
    

    Since the inner class is not static, you need an instance of OuterClass to create the instance of InnerClass on which you can call your method.

    If you make the inner class static, it is also possible to define static methods in InnerClass:

    public class OuterClass implements Interface1 {
    
        public static class InnerClass implements Interface2 {
    
            public void method() {
                System.out.println("hello");
            }
    
            public static void staticMethod() {
                System.out.println("static");
            }
        }
    }
    

    In this scenario you don't need an instance of OuterClass to construct an instance of InnerClass as it is statically available and not bound to an instance. Additionally, you can call static methods of the inner class without an instance of the InnerClass:

    // call static method without any instance
    OuterClass.InnerClass.staticMethod();
    
    // create instance of inner class without instance of outer class
    OuterClass.InnerClass inner = new OuterClass.InnerClass();
    inner.method(); // call method of inner class
    
    // output: static
               hello