Home  >  Q&A  >  body text

java - abstract inner class + generics

Simple inner class usage:

public class OuterClass {
    public OuterClass() {
    }

    public abstract class InnerAbstractClass {
        public void a() {

        }
        public abstract void absMethod();
    }
    
    public void test() {
        new OuterClass().new InnerAbstractClass() {
            public void absMethod() {

            }
        };
    }
    
    public static void main(String[] args) {

        new OuterClass().new InnerAbstractClass() {
            public void absMethod() {

            }
        };
    }
}

Add generics to the above example

public class OuterClass<T> {
    public OuterClass() {
    }

    public abstract class InnerAbstractClass {
        public void a() {

        }
        public abstract void absMethod();
    }

    public void test() {
        new OuterClass().new InnerAbstractClass() {
            public void absMethod() {

            }
        };
    }

    public static void main(String[] args) {

        new OuterClass().new InnerAbstractClass() {
            public void absMethod() {

            }
        };
    }
}

Call the inner class in the test method and compile correctly. An error is reported in the main method, cannot be referenced from a static context.
No error will be reported if an internal class is called in another newly created class

public class OuterClassTest {
    public static void main(String[] args) {
        new OuterClass().new InnerAbstractClass() {
            public void absMethod() {

            }
        };
    }
}

Why? ? ?

给我你的怀抱给我你的怀抱2713 days ago824

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-05-17 10:02:28

    Haha, click on the unhelpful person, copy the code and run it yourself, it will compile without any problem! no problem!

    If you don’t know how to use IDE, just use javac

    reply
    0
  • Cancelreply