简体   繁体   中英

What is the use of main method in abstract class?

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(String args[])
         {                        

            System.out.println("Abstract Class main method : ");

         }
 }

We can not create the object of abstract class ,so what is the use of main method in abstract class ?

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.

您可以扩展抽象类,然后子类有一个main方法,而不指定那个。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM