Java-静态方法
时间:2020-02-23 14:36:53 来源:igfitidea点击:
在本教程中,我们将学习Java编程语言中类的静态方法。
在上一教程中,我们了解了类的静态变量。
当我们想要一个可以独立于该类任何对象使用的类方法时,我们创建一个"静态"方法。
静态方法具有以下限制。
静态方法只能调用静态方法。
静态方法只能访问静态变量。
我们不能在静态方法中使用this和super关键字。
注意! " super"关键字用于从子类中调用父类的构造函数。
我们将在继承教程中学习super关键字。
静态方法的语法
static returnType methodName() {
//some code ...
};
其中,returnType是一些有效的返回类型,而methodName是静态方法的名称。
调用静态方法
要调用静态方法,我们必须使用以下语法。
ClassName.methodName();
其中," ClassName"是类的名称," methodName"是类的静态方法的名称。
例
在下面的示例中,我们具有HelloWorld类,并且它具有一个静态整数变量objectCount。
每当创建类的新对象时,此静态变量的值就会增加。
我们也有getCount()和resetCount()静态方法来分别获取和重置objectCount变量的值。
class HelloWorld {
//static variable
static int objectCount = 0;
//variable
private int number;
//constructor
HelloWorld(int number) {
this.number = number;
//updating the static variable
HelloWorld.objectCount++;
}
//static method
static void resetCount() {
objectCount = 0;
}
static int getCount() {
return objectCount;
}
//method
public int getNumber() {
return this.number;
}
}
public class Example {
public static void main(String[] args) {
System.out.println("Total number of objects of the Hello World class: " + HelloWorld.objectCount);
//create an object
System.out.println("Creating object obj.");
HelloWorld obj = new HelloWorld(10);
System.out.println("Total number of objects of the Hello World class: " + HelloWorld.objectCount);
System.out.println("Hello World obj number: " + obj.getNumber());
//create another object
System.out.println("Creating object obj2.");
HelloWorld obj2 = new HelloWorld(20);
System.out.println("Total number of objects of the Hello World class: " + HelloWorld.objectCount);
System.out.println("Hello World obj2 number: " + obj2.getNumber());
System.out.println("Resetting object count of the Hello World class.");
HelloWorld.resetCount();
System.out.println("Total number of objects of the Hello World class after reset: " + HelloWorld.getCount());
}
}
$javac Example.java $java Example Total number of objects of the Hello World class: 0 Creating object obj. Total number of objects of the Hello World class: 1 Hello World obj number: 10 Creating object obj2. Total number of objects of the Hello World class: 2 Hello World obj2 number: 20 Resetting object count of the Hello World class. Total number of objects of the Hello World class after reset: 0
因此,在上面的代码中,我们创建了" HelloWorld"类的两个对象。
每次实例化一个对象时,我们都会使用" ++"增量操作符将静态变量" objectCount"的值增加1。
最后,我们调用resetCount()静态方法来重置静态变量,并调用getCount()静态方法来获取静态变量的值。

