I'm having a lot of trouble understanding the difference between a static method and a regular method in Java. I understand there are already a lot of questions relating to this, however none I have seen show a side by side comparison of a static and non static method accomplishing the same task.
This is the static method I have that I'm trying to change to a regular method.
public static String getString(Scanner sc, String prompt)
{
System.out.print(prompt);
String s = sc.next();
sc.nextLine();
return s;
}
And this is where I call it in another class
String productCode = Validator.getString(sc, "Enter product code: ");
How would I change this to make it a regular method and work when I call it?
Implementation:
public String getString(Scanner sc, String prompt)
{
System.out.print(prompt);
String s = sc.next();
sc.nextLine();
return s;
}
Usage:
new Validator(...).getString(sc , "...");
A method can be either static
or dynamic
(non static
). When a method is static
, it belongs to the class. When a method is dynamic, it belongs to each specific instance of your class. That being said, removing the keyword static
, creates an instance of your class and calls this method on that object.
In terms of code:
public String getString(Scanner sc, String prompt)
{
}
// Use the suitable constructor here.
Validator validator = new Validator();
String productCode = validator.getString(sc, "Enter product code: ");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.