简体   繁体   English

Java中的“覆盖”主要目的是什么?

[英]What purpose does “overriding” main serve in Java?

this is how we can override main function in java.... 这就是我们如何覆盖Java中的main函数的方法。

public class animaltest 
{
    public static void main(String[] args)  
    {
        horse h = new horse();
        h.eat();
    }
}

public class inheritmain extends animaltest 
{
    public static void main(String[] args)  
    {
        System.out.print("main overrided");
    }
}

but what is the benefit of overriding main?? 但是重写main的好处是什么?

static methods do not override: they are shadowed. static方法不会覆盖:它们被阴影覆盖。 There are two different independent static methods in that case, namely animaltest.main and inheritmain.main . 在这种情况下,有两种不同的独立静态方法,分别是animaltest.maininheritmain.main (See Can we override static method in Java? ) (请参阅我们可以在Java中重写静态方法吗?

The "advantage" -- if any ;-) -- is that the program can be started/launched from either class as both classes implement the main method : “优势”(如果有的话,-))是该程序可以从任一类启动/启动,因为这两个类都实现了main方法

The main method is similar to the main function in C and C++; main方法类似于C和C ++中的main函数; it's the entry point for your application and will subsequently invoke all the other methods required by your program. 它是应用程序的入口点,随后将调用程序所需的所有其他方法。

Happy coding. 快乐的编码。

Overriding is not for STATIC functions, overriding is only for member functions which are not static. 覆盖不适用于STATIC函数,覆盖仅适用于非静态成员函数。

In this case, No POLYMORPHIC will be observed. 在这种情况下,将不会观察到POLYMORPHIC

I dont think you can override main in Java because you don't inherit main from any class in the first place. 我认为您不能在Java中覆盖main,因为您一开始就不会从任何类继承main。 Hence there is nothing to be overriden. 因此,没有什么可以替代的。

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

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