Main method override in java

Java main() method explained with examples

In this article, we will learn Java main() method in detail. As the name suggest this is the main point of the program, without the main() method the program won’t execute.

What is a main() method in Java?

The main() method is the starting point of the program. JVM starts the execution of program starting from the main() method.

Syntax of main() method:

public static void main(String args[])

public: We have already learned in the access specifier tutorial that public access specifier allows the access of the method outside the program, since we want the JVM to identify the main method and start the execution from it, we want it to be marked “public”. If we use other access modifier like private, default or protected, the JVM wouldn’t recognise the main() method and the program won’t start the execution.

static: The reason the main() method is marked static so that it can be invoked by JVM without the need of creating an object. In order to invoke the normal method, we need to create the object first. However, to invoke the static method we don’t need an object. Learn more about static method here.

Читайте также:  Javascript create input element

void: This is the return type. The void means that the main() method will not return anything.

main(): This the default signature which is predefined by JVM. When we try to execute a program, the JVM first identifies the main() method and starts the execution from it. As stated above, the name of this method suggests that it is the “main” part of the program.

String args[]: The main method can also accepts string inputs that can be provided at the runtime. These string inputs are also known as command line arguments. These strings inputs are stored in the array args[] of String type.

Can we have main() method defined without String args[] parameter?

If we have a main() method without String args[] in a program, the program will throw no compilation error however we won’t be able to run the program as the JVM looks for the public main method with the String args[] parameter and if it doesn’t find such method, it doesn’t run the program.

Error: Main method not found in class JavaExample, please define the main method as: public static void main(String[] args)

As you can see that the program threw error at runtime.

Java – static block vs main method

As we learned in the previous article, static block is used to initialise the static data members. Let’s run a program with static block and main method (static method) to see in which order they run.

class JavaExample < //static block static < System.out.println("Static Block"); >//static method public static void main(String args[]) < System.out.println("Main Method"); >>

As we can see, the static block executed before the main method.

What if a program doesn’t have a main method?

Let’s write a program without the main method to see whether it runs or not.

Error: Main method not found in class JavaExample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

Different ways to write main method in java

The following are the valid ways to write a main method in java:

public static void main(String[] args) //We can interchange static and public static public void main(String[] args) //We can place the square brackets at the different locations public static void main(String[] args) public static void main(String []args)

Overloading of main() method in Java

We can overload the main method in Java. This allows us to have more than one main() method in Java. However the signature of all the overloaded methods must be different. To learn more about overloading, refer this guide: Method overloading in Java.

class JavaExample < public static void main(String args[]) < System.out.println("main method"); main(100); main('A'); >//Overloaded int main method public static void main(int a) < System.out.println(a); >//Overloaded char main method public static void main(char ch) < System.out.println(ch); >>

Frequently Asked Questions

The main method is used to specify the starting point of the program. This is the starting point of our program from where the JVM starts execution of the program.

No, you can’t declare a method inside main() method.

Yes we have can more than one main methods in java, however JVM will always calls String[] argument main() method. Other main() methods will act as a Overloaded method. In order to invoke these overloaded methods, we have to call them explicitly.

No, we cannot override main method of java because it is a static method and we cannot override a static method. The static method in java is associated with class which is why we don’t need an object to call these. Therefore, it is not possible to override the main method in java.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Can we override the main method in java?

Overriding is one of the mechanisms to achieve polymorphism. This is the case when we have two classes where one inherits the properties of another using the extends keyword and, these two classes have the same method including parameters and return type (say, sample()).

Since it is an inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the subclass (object).

When we invoke this method (sample) JVM calls the respective method based on the object used to call the method.

Example

class Super < public static void sample()< System.out.println("Method of the superclass"); >> public class OverridingExample extends Super < public static void sample()< System.out.println("Method of the subclass"); >public static void main(String args[]) < Super obj1 = (Super) new OverridingExample(); OverridingExample obj2 = new OverridingExample(); obj1.sample(); obj2.sample(); >>

Output

Method of the superclass Method of the subclass

Overriding Static methods

When superclass and subclass contain the same method including parameters and if they are static. The method in the superclass will be hidden by the one that is in the subclass.

This mechanism is known as method hiding in short, though super and subclasses have methods with the same signature if they are static, it is not considered as overriding.

Overriding main method

You cannot override static methods and since the public static void main() method is static we cannot override it.

Example

class Super < public static void main(String args[]) < System.out.println("This is the main method of the superclass"); >> class Sub extends Super < public static void main(String args[]) < System.out.println("This is the main method of the subclass"); >>
public class MainOverridingExample < public static void main(String args[]) < MainOverridingExample obj = new MainOverridingExample(); Super.main(args); Sub.main(args); >>

Output

This is the main method of the superclass This is the main method of the subclass

Источник

Can you Overload or Override main method in Java? Example

One of the common doubts among Java beginners while learning the overloading and overriding concept is, whether it’s possible to overload the main in Java? Can you override the main method in Java? How will JVM find if you change the signature of the main method as part of the method overloading? etc. These are good questions and show the curiosity and application of knowledge of students, so if you are the tutor you must answer these questions. If you don’t know the answer to this question, don’t worry, just read this article till the end and you will find the answer yourself. I have tried to explain in simple words but if you still can’t get it, feel free to comment and I will try to help you personally.

The short answer to, can we overload the main method in Java is Yes, you can overloading, nothing stops from overloading, but JVM will always call the original main method, it will never call your overloaded main method.

You will learn this in little more detail later, now coming to the next question, can you override the main method in Java? the answer is No because the main is a static method and the static method cannot be overridden in Java.

In order to answer this question understanding of overloading and overriding is necessary. You should know that overloading takes place at compile time and overriding takes place at runtime. You should also be familiar with the rules of method overloading and overriding in Java.

Though main() is a special method because it’s the entry point of your Java application, it follows the same rule of method overriding and overloading as any other method. In this article, you will learn how to overload the main method to see whether JVM calls the original, standard main with string argument or not.

Overloading the main method in Java

Here is how you can overload the main method in Java. This is just one way, you can create as many versions of the main as you want, but you must make sure that the method signature of each main is different.

You can change the method signature by changing the type of argument, the number of arguments, or the order of arguments.

The best practice to overload a method or constructor is by changing the number of arguments, or types of arguments. Overloading methods just by changing the order of arguments may create confusion and increase the chance of calling the wrong method. It’s worth remembering that,

Can we overload main method in Java

Code Example of Overloading Main Method in Java

/** * Java Program to show that you can overload main method in Java * but you cannot override main method. * * @author Javin Paul */ public class Helloworld < /** * Standard main method, JVM will only call this method * even if you provided multiple overloaded version. * */ public static void main(String[] args) < System.out.println("Inside main(String[] args) method . "); > /** * An overloaded main method which accepts Integer[] instead of * String[] as argument. * @param args */ public static void main(Integer[] args)< System.out.println("Inside main(Integer[] args) method . "); > /** * Another overloaded main method which accepts Double[] instead of * String[] as argument. * @param args */ public static void main(Double[] args)< System.out.println("Inside main(Double[] args) method . "); > > Output Inside main(String[] args) method .

In this example, you can see that we have two main methods, one accepts String array as an argument and the other accept Integer array as an argument, but you can see that when you run our program from the command line, only the main method with string array as an argument is called.

There was no error, no ambiguity, JVM will always call this main method, no matter how many overloaded main methods you will put on this class. Then questions come how do you call your overloaded main? Well, you can call it just like any other method.

Simply calling main(new int[]) from the original main method will invoke your overloaded main with integer array as an argument. Since there is no compilation error, it proves that you can overload the main method in Java.

Regarding Overriding we have already proven that the static method cannot be overridden, they can only be hidden. See that post to learn this concept by following an example. In short, the main method can be overloaded but cannot be overridden in Java.

Main method can be overloaded but cannot overridden in Java

That’s all about overloading and overriding the main method in Java. Now you know that it’s possible to overload main in Java but it’s not possible to override it, simply because it’s a static method. Execution of Java program has no impact on overloading main because JVM always calls the original main method and if it doesn’t found in class then it throws java.lang.NoSuchMethodError: main Exception in thread «main» error at runtime.

  • 130+ Java Interview Questions from the last 5 years (questions)
  • Understanding the Helloworld Program in Java (explanation)
  • How to run a Java program from the command prompt? (example)
  • 10 things Every Java programmer should know about the main method (article)
  • Can you run a Java program without the main method? (answer)
  • What is the difference between PATH and CLASSPATH in Java? (answer)
  • What is a .class file in Java? How does it work? (answer)
  • 40 Binary Tree-Based Algorithms Questions (BST problems)
  • Top 5 Object Oriented Design Interview Questions (OOP questions)
  • How to make executable JAR in Eclipse? (steps)
  • 20+ System Design Questions for Coding interviews (design questions)
  • Difference between Overloading, Overriding, and Shadowing (answer)
  • How to run a Java program from the JAR file? (example)
  • 10 Best System Design Courses for Interviews (system design courses)
  • The Complete Java Developer RoadMap (guide)
  • Top 30 Linked List Interview Questions (linked list problems)

P. S. — If you are new to the Java world and looking for a free online course to start learning Java then I highly recommend you check out this Java Tutorial for Complete Beginners(FREE) course by John Purcell on Udemy. It’s completely free and you just need an Udemy account to join this course.

Источник

Оцените статью