-1

Why abstract class in Java can't be static ?

static abstract class A {
    abstract void display();
}

class B extends A {
    void display() {
        System.out.println("Inside class A");
    }
}

public class Main {
    public static void main(String[] args) {
        A b = new B();
        b.display();
    }
}

Above code is giving error: modifier static not allowed here
Tried to understand but couldn't figure it out.

shanfeng
  • 503
  • 2
  • 14
xyz xyz
  • 11
  • 1
  • 2
    Unmitigated gave you an excellent response below: https://stackoverflow.com/a/76069682/421195. The issue (the source of your compiler error) is that a static class should be *nested* in another class. You can read more here: https://stackoverflow.com/a/16147445/421195 or here: https://www.javatpoint.com/why-we-use-static-class-in-java – paulsm4 Apr 21 '23 at 03:36
  • Q: Do you understand what Unmitigated was trying to say? And why parts of JgWangdu's response was misleading? The central issue is *YOU CAN'T CREATE A STATIC TOP-LEVEL CLASS*. For any toplevel class, abstract or not. EXPLANATION: https://stackoverflow.com/a/7370832/421195, https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.5.1 – paulsm4 Apr 21 '23 at 16:17

1 Answers1

4

The static modifier would only make sense if the class is defined inside another class. static class is also illegal in that context; this has nothing to do with it being abstract.

All of the following are valid:

abstract class A {}
public class Main {
    static abstract class B {}
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80