我想知道什么时候使用静态方法?假设我有一个类,有几个getter和setter,一个或两个方法,我希望这些方法只能在类的实例对象上调用。这是否意味着我应该使用静态方法?
例子:
Obj x = new Obj();
x.someMethod();
或:
Obj.someMethod(); // Is this the static way?
我很困惑!
我想知道什么时候使用静态方法?假设我有一个类,有几个getter和setter,一个或两个方法,我希望这些方法只能在类的实例对象上调用。这是否意味着我应该使用静态方法?
例子:
Obj x = new Obj();
x.someMethod();
或:
Obj.someMethod(); // Is this the static way?
我很困惑!
当前回答
如果将静态关键字应用于任何方法,则称为静态方法。
静态方法属于类,而不是类的对象。 不需要创建类实例而调用的静态方法。 方法可以访问静态数据成员,并可以更改它的值。 静态方法可以通过类名。静态名来访问。示例:Student9.change(); 如果要使用类的非静态字段,则必须使用非静态方法。
//改变所有对象的公共属性的程序(静态字段)。
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Indian");
Student9 s2 = new Student9 (222,"American");
Student9 s3 = new Student9 (333,"China");
s1.display();
s2.display();
s3.display();
} }
O/P: 111印度BBDIT 222美国BBDIT 333中国BBDIT
其他回答
当您不想在代码中创建对象来调用方法时,只需将该方法声明为静态方法。因为静态方法不需要调用实例,但这里的问题是,并不是所有的静态方法都由JVM自动调用。此特权仅由main()节点享有。“public static void main[字符串…]方法,因为在运行时,这是方法Signature public“static”void main[], JVM寻求作为开始执行代码的入口点。
例子:
public class Demo
{
public static void main(String... args)
{
Demo d = new Demo();
System.out.println("This static method is executed by JVM");
//Now to call the static method Displ() you can use the below methods:
Displ(); //By method name itself
Demo.Displ(); //By using class name//Recommended
d.Displ(); //By using instance //Not recommended
}
public static void Displ()
{
System.out.println("This static method needs to be called explicitly");
}
}
输出: 这个静态方法由JVM执行 这个静态方法需要显式调用 这个静态方法需要显式调用 这个静态方法需要显式调用
静态方法与实例不关联,因此它们不能访问类中的任何非静态字段。
如果方法不使用类的任何字段(或仅使用静态字段),则使用静态方法。
如果使用类的任何非静态字段,则必须使用非静态方法。
静态方法是一种不需要初始化任何对象就可以调用的方法。你注意到静态是用在Java的main函数中吗?程序从那里开始执行,不需要创建对象。
考虑下面的例子:
class Languages
{
public static void main(String[] args)
{
display();
}
static void display()
{
System.out.println("Java is my favorite programming language.");
}
}
java中的静态方法属于类(而不是类的实例)。它们不使用实例变量,通常从参数中获取输入,对其执行操作,然后返回一些结果。实例方法与对象相关联,并且,顾名思义,可以使用实例变量。
使用静态方法的唯一合理的地方可能是Math函数,当然main()必须是静态的,也可能是小型工厂方法。但是逻辑不应该保存在静态方法中。