Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class having a main?

Tags:

java

Would using a main for an abstract class be bad practice in general or is it permissible due to the nature of Abstract classes being able to have a body?

like image 606
sgript Avatar asked Mar 17 '23 12:03

sgript


1 Answers

Sure, an abstract class can have a main method, just as any class can have a main, and in fact it is one way of testing the abstract class -- if you create a concrete implementation of it within the main method. The only thing that you cannot do with an abstract class is to construct them as is, without extending them and implementing all abstract methods.

public abstract class Foo {
    public abstract void bar();

    public static void main(String[] args) {
        // anonymous inner class representation
        Foo foo = new Foo() {
            // must implement all abstract methods
            public void bar() {
                System.out.println("bar");
            }
        };
        foo.bar();
    }
}

Edit: good point by VitalyGreck:

abstract classes are abstract because they don't implement some methods in their body. having bar() implemented inside the main() method (even static) confuses users of your class. Good practice is to make two separate classes, one of them - abstract, another - with implementation and static method enclosed. Or dynamically find the enclosing class (see stackoverflow.com/questions/936684/…) using reflection.

In other words -- just because it can be done, doesn't mean that it should be done.

like image 182
Hovercraft Full Of Eels Avatar answered Mar 29 '23 11:03

Hovercraft Full Of Eels