[英]Java: Static Method vs Non Static Method
I'm having a lot of trouble understanding the difference between a static method and a regular method in Java.我在理解 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
).方法可以是
static
或dynamic
(非static
)。 When a method is static
, it belongs to the class.当一个方法是
static
,它属于类。 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.话虽如此,删除关键字
static
,创建类的实例并在该对象上调用此方法。
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: ");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.