The following code simply prints the word "hi" when run.
import java.util.*;
import java.io.*;
class poly
{
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
public static void main(String args[]) throws Exception
{
System.out.println("hi");
}
}
Is there a way to overload the main() method?
Your program only starts at one location, so that makes no sense. Furthermore, polymorphism is a totally different concept; that's called overloading, not polymorphism.
What you are trying to do is overloading the main method, not making it polymorphic. And no, you can't do it (or to be precise: overload you can, just the JVM won't call the overloaded versions). The JVM is looking for a main method with a specific signature, namely taking a String[] parameter.
Maybe if you tell us more about the actual problem you are trying to solve, we can offer alternative solutions.
The code is correct, you've overloaded the main method. But, as Peter mentioned, the main thread of an application will always start at the method with the signature
public static void main(String[] args)
and nothing else. For starting an application, JVM will ignore all other main methods. To execute the content, you'll have to call it in your code, like so:
public static void main(String args[]) {
main("me");
}
(Should print "this is me" to the console)
In brief you can overload a main function like:
class A
{
public static void main(String s) {
System.out.println(s);
}
public static void main(int s) {
System.out.println(s);
}
public static void main(String args[])
{
System.out.println("inside main entry");
main("me");
}
}
Output:
inside main entry
me
We can have any number of main method and that can be overloaded but the main thread of an application will always start at the method with the signature:
public static void main(String[] args)
and nothing else.
In Java args contains the supplied command-line arguments as an array of String objects.
You can overload a main method in Java; however, getting the classloader to start from the overloaded main method is going to be quite a trick.
The class you pass the the java executable is inspected, it's static methods are read, and control is passed off to only the one that looks like
public static void main(String[] args) { ... }
Since this is a static method, and Java does not have the concept of inheriting static methods, you have no way to overload this method. Since Java does not have the concept of inheritance of static methods, sub-classing the static bits of a class is a nonsensical idea.
Maybe you want something like this?
import java.util.*;
import java.io.*;
class poly {
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
public static void main(String args[])throws Exception
{
if (args.length == 1) {
poly.main(args[0]);
}
else {
System.out.println("hi");
}
}
}
The java runtime environment only looks for the exact match to public static void main(String[]), which is defined as the entry-point for standalone java applications.
To simulate the behaviour you want you have to call the other main yourself:
/**
* Your method called main, ignored by the java runtime since
* it does not match the signature. Called by the valid main(String[])
**/
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
/**
* Starting point of your program, called by the java runtime.
*/
public static void main(String args[])throws Exception
{
if(args.length >= 1){
main(args[0]);
}else{
System.out.println("hi");
}
}
As others point out having several methods with the same name but different parameters is called over*loading* and not polymorphism (over*writing*).
I'm not quite sure what you are asking but I don`t see any reason why you cannot overload the main method.
The "main method I think you are referring to is
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
To overload this method I would create a method such as
public static void main(){}
This must be in the same class as the other main method to make it overloaded.
The static keyword means common to the class.....(there is no need to use an object to access the method from the main(String[] args) method.
In my ind creating an overloaded method in a class is the same as creating a different method.
Different arguments, parameter list ====> different signature ======> different method.
I hope this helps.
Related
This program must print final parametres about a TV state in three (3) rows...
in first row...on which level loudness is...
in the second on which program is (1., 2., 56, etc...)
third row - is it turned on...
(after all operations inside programm)... this programm is pasted from manual for Java...
class Television {
int volumeTone = 0;
int channelNow = 1;
boolean turnedOn = false;
void turnOn(){
turnedOn = true;
}
void turnOff(){
turnedOn = false;
}
void increaseVolume(){
volumeTone = volumeTone + 1;
}
void decreaseVolume(){
volumeTone = volumeTone - 1;
}
void turnOffVolume(){
volumeTone = 0;
}
void changeChannelUp(){
channelNow = channelNow + 1;
}
void changeChannelDown(){
channelNow = channelNow - 1;
}
int returnChannelBefore(){
return channelNow;
}
int returnToneVolume(){
return volumeTone;
}
boolean isItTurnedOn(){
return turnedOn;
}
void writeParametres(){
System.out.println("Volume loudness now is "+volumeTone);
System.out.println("Channel now is "+channelNow);
System.out.println("Tv is turned on? "+turnedOn);
}
}
You need to have a main method in the class to run...
Your exception itself say that, please define the main method as:public static void main(String[] args)
You need main method in your class Television as shown below.
public static void main(String[] args)
{
//Your logic run this class
}
In Java, you need to have a method named main in at least one class.
Please refer this link about main method.
Without a main method, you will not be able to run anything. Create a new class with a main method like so:
public class myClass
{
public static void main(String [] args)
{
//Here you can create an instance of your television class
Television tel = new Television();
//You can then call methods on your newly created instance
tel.turnOn();
}
}
The main entrance to a java application is with a static main method
which is usually defined as;
public static void main(String []args)
{
}
If you want to run any class make sure it has this method.
You will need to Implement main method
From The Java Tutorials' Hello World Example: (emphasis mine)
In the Java programming language, every application must contain a main method whose signature is: public static void main(String[] args)
...
The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.
In other words, when running a Java class, the JVM will look for a main() method in it. That method will be called automatically when running the class, and will be the entry point for the execution flow of the program.
Also, take a look at How does the main method work?.
Can we call main method inside main?
public static void main(String[] args) {
main({"a","b","c"});
}
Tried to google.Can't find the link.
Sorry if the question is trivial
You can but using the correct format
main(new String[] {"a","b","c"});
should give StackOverFlowError (not tested)
You will get StackOverFlowError. If you call endless recursive calls/deep function recursions.
Thrown when a stack overflow occurs because an application recurses
too deeply.
You need to pass String array like
main(new String[] {"a","b","c"});
You can. And it is very much legal.
Also, it doesn't necessarily give a StackOverFlowError:
public static void main(String args[]){
int randomNum = (int)(Math.random()*10);
if(randomNum >= 8)
System.exit(0);
System.out.print("Heyhey!");
main(new String[]{"Anakin", "Ahsoka", "Obi-Wan"});
}
Just saying.
Kugathasan is right.
Yes it does give StackOverflow Exception. I tested it right now in Eclipse.
class CallingMain
{
public static void main(String[] args)
{
main(new String[] {"a","b","c"});
}
}
I have one suggestion, I think the best way to eliminate the confusion is to try coding and running it. Helps with lots of doubts.
You can simply pass the argument like main(new String[1]) - this line will call main method of your program. But if you pass "new String[-1]" this will give NegativeArraySizeException. Here I'mm giving an example of Nested Inner Class where I am calling the Main method:
class Outer
{
static class NestedInner
{
public static void main(String[] args)
{
System.out.println("inside main method of Nested class");
}//inner main
}//NestedInner
public static void main(String[] args)
{
NestedInner.main(new String[1] );//**calling of Main method**
System.out.println("Hello World!");
}//outer main
}//Outer
Output:-
inside main method of Nested class
Hello World!
For my programming class, I was told to make a program that uses recursion. I was confused and went to see my friend who was already in the class and he showed me this program. I thought recursion had to use things like r1(x-1), etc. Is it actually recursive? If it's not, how do you make it recursive?
import java.util.*;
import java.io.*;
class ReverseFile
{
private static Scanner infile;
public static void main(String[] args) throws IOException
{
infile= new Scanner(new File("hw_1.txt"));
r1();
}
public static void r1()
{
String s;
if (infile.hasNextLine())
{
s = infile.nextLine();
r1();
System.out.println(s);
}
}
}
It is recursive as r1 calls itself. The fact that no arguments are passed to r1 doesn't matter.
I want to execute one function before main function in C and JAVA language.
I know one way that is, by using #pragma directive in C language. Is there any other way to do that in both languages?
I can think of two simple(-ish) ways to do it in Java:
Method #1 - static initializers
For example:
public class Test {
static {
System.err.println("Static initializer first");
}
public static void main(String[] args) {
System.err.println("In main");
}
}
Method #2 - A proxy main.
public class ProxyMain {
public static void main(String[] args) {
String classname = args[0];
// Do some other stuff.
// Load the class
// Reflectively find the 'public static void main(String[])' method
// Reflectively invoke it with the rest of the args.
}
}
You then launch this as:
java <jvm-options> ... ProxyMain <real-Main> arg ...
There is also a 3rd method, but it requires some "extreme measures". Basically you have to create your own JVM launcher that uses a different scheme for starting the application. Have this do the extra stuff before loading the entry point class and calling its main method. (Or do something different entirely.)
You could even replace the default classloader; e.g. How to change default class loader in Java?
in java you can use static block
public class JavaApplication2 {
static {
System.out.println("in static ");
}
public static void main(String[] args) {
System.out.println("in main ");
}
}
As an extension to the C standard gcc provides the function attribute constructor which allows functions to be called before main().
For details please see here (scroll down). Also this SO question and its answers help on this.
Try combining a static block and a static method containing what you want executed before your main method.
package test;
public class Main {
static {
beforeMain();
}
public static void main(String[] args) {
System.out.println("after");
}
private static void beforeMain() {
System.out.println("before");
}
}
Output:
before
after
It could be the first thing you call from your main function. That way it will run before your "real" main function.
Use that method(what you want to run before main method) as your main method.
Then it is so simple
Or use static block before main()
In java, execution of any other method is possible before main() method execution. We need a static initializer block for that. It starts with a static keyword.
Like:
static {
// statements
}
Now try to understand with actual code implementation.
public class BefourMain {
static int sum;
static {
sum = add(4,5,6);
System.out.println("Calling add() method: " + sum);
System.out.println("\ncalling main");
main(null);
System.out.println("Main end\n");
System.out.println("Now JVM calling main()\n");
}
public static void main(String[] args) {
int sum = add(1,2,3);
System.out.println(sum);
}
static int add(int a, int b, int c) {
return a + b + c;
}
}
Now try to understand with actual code implementation.
When we start executing this code the static initializer block will start execution first, in the static initializer block we are calling the add() method and storing the value in the static variable, and printing it. Next, we are calling the main() method, which will execute. when the static initializer block execution will complete JVM will call the main() method again.
Output
Output of the above code
Can we overload a main() method in Java?
You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM. For example:
public class Test {
public static void main(String[] args) {
System.out.println("main(String[] args)");
}
public static void main(String arg1) {
System.out.println("main(String arg1)");
}
public static void main(String arg1, String arg2) {
System.out.println("main(String arg1, String arg2)");
}
}
That will always print main(String[] args) when you run java Test ... from the command line, even if you specify one or two command-line arguments.
You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.
EDIT: Note that you can use a varargs signature, as that's equivalent from a JVM standpoint:
public static void main(String... args)
Yes, you can overload main method in Java. But the program doesn't execute the overloaded main method when you run your program, you have to call the overloaded main method from the actual main method.
that means main method acts as an entry point for the java interpreter to start the execute of the application.
where as a loaded main need to be called from main.
Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:
class Simple{
public static void main(int a){
System.out.println(a);
}
public static void main(String args[]){
System.out.println("main() method invoked");
main(10);
}
}
It will give the following output:
main() method invoked
10
YES, you can overload main()
But to be clear --
although you can overload main, only the version with the standard signature will be executable as an application from the command line. e.g
public static void main(String a,String... args){
// some code
}
2)public static void main(String[] args){//JVM will call this method to start
// some code
}
Yes, you can overload main method in Java. you have to call the overloaded main method from the actual main method.
Yes, main method can be overloaded. Overloaded main method has to be called from inside the "public static void main(String args[])" as this is the entry point when the class is launched by the JVM. Also overloaded main method can have any qualifier as a normal method have.
Yes, you can.
The main method in Java is no extra-terrestrial method. Apart from the fact that main() is just like any other method & can be overloaded in a similar manner, JVM always looks for the method signature to launch the program.
The normal main method acts as an entry point for the JVM to start
the execution of program.
We can overload the main method in Java. But the program doesn’t
execute the overloaded main method when we run your program, we need
to call the overloaded main method from the actual main method only.
// A Java program with overloaded main()
import java.io.*;
public class Test {
// Normal main()
public static void main(String[] args) {
System.out.println("Hi Geek (from main)");
Test.main("Geek");
}
// Overloaded main methods
public static void main(String arg1) {
System.out.println("Hi, " + arg1);
Test.main("Dear Geek","My Geek");
}
public static void main(String arg1, String arg2) {
System.out.println("Hi, " + arg1 + ", " + arg2);
}
}
Valid variants of main() in Java
Yes,u can overload main method but the interpreter will always search for the correct main method syntax to begin the execution..
And yes u have to call the overloaded main method with the help of object.
class Sample{
public void main(int a,int b){
System.out.println("The value of a is " +a);
}
public static void main(String args[]){
System.out.println("We r in main method");
Sample obj=new Sample();
obj.main(5,4);
main(3);
}
public static void main(int c){
System.out.println("The value of c is" +c);
}
}
The output of the program is:
We r in main method
The value of a is 5
The value of c is 3
yes we can overload main method. main method must not be static main method.
This is perfectly legal:
public static void main(String[] args) {
}
public static void main(String argv) {
System.out.println("hello");
}
Yes. 'main( )' method can be overloaded. I have tried to put in some piece of code to answer your question.
public class Test{
static public void main( String [] args )
{
System.out.println( "In the JVMs static main" );
main( 5, 6, 7 ); //Calling overloaded static main method
Test t = new Test( );
String [] message = { "Subhash", "Loves", "Programming" };
t.main(5);
t.main( 6, message );
}
public static void main( int ... args )
{
System.out.println( "In the static main called by JVM's main" );
for( int val : args )
{
System.out.println( val );
}
}
public void main( int x )
{
System.out.println( "1: In the overloaded non-static main with int with value " + x );
}
public void main( int x, String [] args )
{
System.out.println( "2: In the overloaded non-static main with int with value " + x );
for ( String val : args )
{
System.out.println( val );
}
}
}
Output:
$ java Test
In the JVMs static main
In the static main called by JVM's main
5
6
7
1: In the overloaded non-static main with int with value 5
2: In the overloaded non-static main with int with value 6
Subhash
Loves
Programming
$
In the above code, both static-method as well as a non-static version of main methods are overloaded for demonstration purpose. Note that, by writing JVMs main, I mean to say, it is the main method that JVM uses first to execute a program.
Yes According to my point of view, we are able to overload the main method but method overloading that's it. For Example
class main_overload {
public static void main(int a) {
System.out.println(a);
}
public static void main(String args[]) {
System.out.println("That's My Main Function");
main(100);
}
}
In This Double Back slash Step, I am just calling the main method....
Yes a main method can be overloaded as other functions can be overloaded.One thing needs to be taken care is that there should be atleast one main function with "String args[] " as arguments .And there can be any number of main functions in your program with different arguments and functionality.Lets understand through a simple example:
Class A{
public static void main(String[] args)
{
System.out.println("This is the main function ");
A object= new A();
object.main("Hi this is overloaded function");//Calling the main function
}
public static void main(String argu) //duplicate main function
{
System.out.println("main(String argu)");
}
}
Output:
This is the main function
Hi this is overloaded function
Yes you can Overload main method but in any class there should be only one method with signature public static void main(string args[]) where your application starts Execution, as we know in any language Execution starts from Main method.
package rh1;
public class someClass
{
public static void main(String... args)
{
System.out.println("Hello world");
main("d");
main(10);
}
public static void main(int s)
{
System.out.println("Beautiful world");
}
public static void main(String s)
{
System.out.println("Bye world");
}
}