简体   繁体   English

main方法在抽象类中有什么用?

[英]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 ? 我知道我们可以在抽象类中编写main方法,但是我们可以从中实现什么呢?

 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 ? 我们不能创建抽象类的对象,那么抽象类中main方法的用途是什么?

Abstract just means you can't instantiate the class directly. Abstract只是意味着你无法直接实例化该类。

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. 并且不需要创建类的实例来调用main(),因为它是静态的。 So there's no problem. 所以没有问题。

Abstract just means you can't instantiate the class directly. Abstract只是意味着你无法直接实例化该类。 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. 你可以使用静态方法,包括main(),它们不需要一个对象,所以调用它们就可以了。

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 你的摘要号是:6

As Zeeshan already said, since the main method is static, it does not require an instance to be called. 正如Zeeshan所说,由于main方法是静态的,因此不需要调用实例。 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. 至于通过将main方法放在抽象类中可以实现什么,没有什么比将它放在任何其他类中更多或更少。

Typically, the main method is either placed in a class of its own or in a class that is central to the application. 通常, main方法要么放在自己的类中,要么放在应用程序的中心类中。 If that class happens to be abstract, so be it. 如果那个类恰好是抽象的,那就这样吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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