I know that we can write main method in abstract class, but what we can achieve from it ?
public abstract class Sample
{
public static void main(Strin
Abstract just means you can't instantiate the class directly.
Loading a class is not the same as creating an instance of the class. And there's no need to create an instance of the class to call main(), because it's static. So there's no problem.
Abstract just means you can't instantiate the class directly. You can have constructors if you want - they might be needed for subclasses to initiate the object state. You can have static methods, including main() and they don't need an object so calling them is fine.
So you only got error when you try to create the object, which is when you run into the abstract limitation.
As Zeeshan already said, since the main
method is static, it does not require an instance to be called. As to what can be achieved by placing the main method in an abstract class, well nothing more or less than placing it in any other class.
Typically, the main
method is either placed in a class of its own or in a class that is central to the application. If that class happens to be abstract, so be it.
You can extend the abstract class and then the child class has a main
method without specifying one there.
public abstract class Abstrc
{
Abstrc(){} // constructor
public abstract void run(); // abstract method
public static int mul(){return 3*2;} // static method
public static void main(String[] args)
{ // Static method that can be accessed without instantiation
System.out.println("Your abstract no is : " + Abstrc.mul());
}
}
Your abstract no is : 6