What is the use of main method in abstract class?

后端 未结 4 829
攒了一身酷
攒了一身酷 2021-02-05 10:00

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         


        
相关标签:
4条回答
  • 2021-02-05 10:16

    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.

    0 讨论(0)
  • 2021-02-05 10:19

    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.

    0 讨论(0)
  • 2021-02-05 10:23

    You can extend the abstract class and then the child class has a main method without specifying one there.

    0 讨论(0)
  • 2021-02-05 10:31
    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

    0 讨论(0)
提交回复
热议问题