Wednesday, March 14, 2012

How to inherit from an inner class in Java?


If the inherited inner class is a non-static inner class. This means that it can only be instatiated within the context of an instance of the enclosing class.
class Outer {
    class Inner { 
        void method() { 
            System.out.println("method called"); 
        }
    }
}
public class Program  extends Outer.Inner {
    Program() {
        new Outer().super();
    }
    public static void main(String[] args)  { 
        Program p = new Program();
        p.method();
    }
}
If the inherited inner class is a static inner class (Nested class).
class Outer {
    static class Inner { 
        void method() { 
            System.out.println("method called"); 
        }
    }
}
public class Program  extends Outer.Inner {
    Program() {
    }
    public static void main(String[] args)  { 
        Program p = new Program();
        p.method();
    }
}

No comments:

Post a Comment