• Post Reply Bookmark Topic Watch Topic
  • New Topic

main method invocation possible from another class?  RSS feed

 
vatsalya rao
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Today I came across a question "Is it possible to invoke main method of class A from class B,given both are public classes?"

I tried to do the same like this as Iam not sure of the answer

public class A
{
public static void main(String a[])
{
System.out.println("main method in class A");
}
}


this is A.java

And one more java file is B.java that goes as follows.(Both are in a directory named "java")

import java.*;
public class B
{

public static void main(String ar[])
{
String ab;
System.out.println("this is main in class B");
System.out.println("invoking class A main method from class B ");
A.main(ab);
}
}


When I compiled B.java Iam gettign the error as

main<java.lang.String>in A can not be appiled to <java.lang.String>
A.main(ab)

Did I go wrong anywhere or it is not possible to invoke main method of one class from another class ,like we invoke other methods
 
yue zhang
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ab is a String, but A.main() need a String array
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As yue zhang said, you need to match the signatures.
One way is passing an array (new String[] {ab}), the other is declaring the main method in class A with varargs:

This last approach only works in Java 5 and up.
 
vatsalya rao
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello YueZang,RobPrime,

Thank you both of you for making me to realise my mistake.

Thanks a ton.i declared the variable 'ab" as

String [] ab={"abc"}

and invoked main method of A in class B.

The program ran successfully and key point I learnt is

We can invoke main methof of one class from another.

Thanks once again.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by vatsalya rao:
...We can invoke main methof of one class from another...

As you know, main is special because it can be invoked from the command line. But in all other respects, it's no different than any other method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!