Reputation: 17
I have a Java program in which I need to accept the command line arguments in an array as input in the main
method, and then need to pass the array to a constructor of another class in the same program. I need to know how to declare the array globally and then how to pass it and take it in the constructor.
Thanks
Upvotes: 0
Views: 4912
Reputation: 9456
public class Example{
Example(String s[])
{
AnotherClass ac = new AnotherClass(s);
}
public static void main(String[] args){
int num=args.length;
String s[]=new String[num];
Example ex = new Example (s);`
}
}
And you can create AnotherClass
public class AnotherClass{
AnotherClass(String s[])
{
// array argument constructor
}
}
You can run using
javac Example.java
java Example
Upvotes: 1
Reputation: 14053
In your class that contains the main method, you could have a class variable like:
String[] cmdLineArgs;
then in the main method:
cmdLineArgs = new String[args.length];
this.cmdLineArgs = args;
and then just implement a getter that will return cmdLineArgs
. Then to call another constructor:
YourObject x = new YourObject(yourFirstClass.getCmdLineArgs());
(you don't need all those steps if you're calling this other constructor from the main method of course, you can just call the constructor with args
directly)
Upvotes: 0
Reputation: 25695
class SomeOtherClass{
public SomeOtherClass(String[] args){
this.arguments = args;
}
private String[] arguments;
}
class YourMainClass{
public static void main(String[] args){
SomeOtherClass cl = new SomeOtherClass(args);
//fanny's your aunt
}
}
This is how you can pass the arguments to SomeOtherClass's constructor.
Upvotes: 0