Java 抽象类中的main方法有什么用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21967340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the use of main method in abstract class?
提问by snehal
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方法有什么用呢?
回答by GhostGambler
You can extend the abstract class and then the child class has a main
method without specifying one there.
您可以扩展抽象类,然后子类有一个main
方法,而无需在那里指定一个方法。
回答by Zeeshan
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.
加载类与创建类的实例不同。并且不需要创建类的实例来调用 main(),因为它是静态的。所以没有问题。
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.
抽象只是意味着你不能直接实例化这个类。如果需要,您可以拥有构造函数 - 子类可能需要它们来启动对象状态。您可以使用静态方法,包括 main() 并且它们不需要对象,因此调用它们就可以了。
So you only got error when you try to create the object, which is when you run into the abstract limitation.
因此,只有在尝试创建对象时才会出错,也就是在遇到抽象限制时。
回答by alsed42
As Zeeshanalready 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.
正如Zeeshan已经说过的,由于该main
方法是静态的,因此不需要调用实例。至于将 main 方法放在抽象类中可以实现什么,无非是将其放在任何其他类中。
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.
通常,该main
方法要么放置在它自己的类中,要么放置在应用程序中心的类中。如果那个类碰巧是抽象的,那就这样吧。
回答by SDV
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