[Java] Some thing about inner classes

  • If you’re defining an anonymous inner class and want to use an object that’s defined outside the anonymous inner class, the compiler requires that the outside object be final.
  • If you don’t need a connection between the inner class object and the outer class object, then you can make the inner class static. So, it means:
    1. You don’t need an outer-class object in order to create an object of a static inner class.
    2. You can’t access an outer-class object from an object of a static inner class.
  • Non-static inner classes cannot have static data, static fields, or static inner classes. However, static inner classes can have all of these.
  • Normally an interface can't have any code, but static inner class can be part of an interface.
  • It’s not possible to create an object of the inner class unless you already have an object of the outer class. This is because the object of the inner class is quietly connected to the object of the outer class that it was made from. However, if you make a static inner class, then it doesn’t need a reference to the outer class object.
  • An example demonstrates how to inherit from an inner class and how to refer to an enclosing class from within an inner class:

  • class WithInner {
    private int i;
    WithInner(int i){
    this.i = i;
    class Inner {
    public String toString(){
    return WithInner.this.toString();
    public String toString() {
    return "WithInner " + i;

    public class InheritInner extends WithInner.Inner {
    //! InheritInner() {} // Won't compile
    InheritInner(WithInner wi) {
    public static void main(String[] args) {
    WithInner wi = new WithInner(1);
    InheritInner ii = new InheritInner(wi);


Popular posts from this blog

Several possible attacking modes on XRP ledger