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?
The
public Test(...)is a constructor and its purpose is for object creation. This is clearly seen from the sample code…The variable
objis instantiated with objectTestby being assigned to theTest‘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 constructorTestis found in Test.java).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: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.