Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments in main method in java class

Tags:

java

Can someone tell me what is the need to declare a class like this:

public class Test {

 String k;
 public Test(String a, String b, String c){
  k = a + " " + b + " " + c; //do something

 }

 public void run(){
  System.out.println(k);
 }

 public static void main(String[] args) {
  String l = args[0];
  String m = args[1];
  String n = args[2];
  Test obj = new Test(l,m,n);
  obj.run();
 }

}

Of course it works but I don't get the point why would one use such way to implement something. Is it because we need to pass arguments directly to the class main method that is why we use this way or is there some other reason?

What is the purpose of public Test(...) using the same class name. Why is it like this?

like image 562
Rizwan Avatar asked Sep 11 '26 04:09

Rizwan


1 Answers

The public Test(...) is a constructor and its purpose is for object creation. This is clearly seen from the sample code...

Test obj = new Test(l,m,n);

The variable obj is instantiated with object Test by being assigned to the Test's constructor. In java, every constructor must have the exact same name (and case) as the java file it's written in (In your case constructor Test is found in Test.java).

...Why is it like this?

It all depends on what you want to do with your object. You could have a zero-argument constructor (i.e. requires no parameters) and have methods to set your l, m, n, like so:

package net;


public class Test {

    private String k;

    /**
     * 
     */
    public Test() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void set(String a, String b, String c) {
         k = a + " " + b + " " + c; //do something
    }

    public void run() {
        System.out.println(k);
    }

    public static void main(String[] args) {
        String l = args[0];
        String m = args[1];
        String n = args[2];
        Test obj = new Test();
        obj.set(l, m, n);
        obj.run();
    }
}

As you can see, it's exactly the same feature as your example but with a zero-argument constructor.

If your class has no constructor at all, java adds a public zero-argument constructor for you automatically.

Hope this helps.

like image 123
Buhake Sindi Avatar answered Sep 12 '26 18:09

Buhake Sindi