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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With