This is definitely not the way you want to use classes and static variables. It completely depends on how you want to use the specific class. If you want to have the same variables in all instances or no instances at all, you should use it like this:
class TestStatic {
private static String url;
private static String user;
static void print() {
System.out.println(url);
System.out.println(user);
}
public static setUrl(String url){
TestStatic.url = url;
}
public static setUser(String user){
TestStatic.user = user;
}
}
public class Main {
public static void main(String[] args) {
TestStatic.setUrl("HTTP");
TestStatic.setUser("USER");
TestStatic.print();
}
}
So you wouldn't have to create instances at all. Just keep in mind that static variables are changed for ALL instances and that there are no instances needed to access/change them.
If you want the variables to be different for each instance you should approach it like this:
class TestStatic {
private String url;
private String user;
public TestStatic(String url, String user) {
this.url = url;
this.user = user;
}
public void print() {
System.out.println(url);
System.out.println(user);
}
}
public class Main {
public static void main(String[] args) {
TestStatic test = new TestStatic("HTTP", "USER");
test.print();
}
}
Note that you are not using static variables for instance-specific values.
Take a look at this for more information about static variables and methods.
As I read in your comment to Farhan Qasim's answer, your use case would (as he mentioned as well) need a singleton pattern. Just google what it is and what it does or just click this.