静态方法是无需实例化类即可调用的方法。如果要调用超类的静态方法,则可以使用类名直接调用它。
public class Sample{
public static void display(){
System.out.println("This is the static method........");
}
public static void main(String args[]){
Sample.display();
}
}输出结果
This is the static method........
如果您使用实例调用静态方法,它也将起作用。但是,不建议这样做。
public class Sample{
public static void display(){
System.out.println("This is the static method........");
}
public static void main(String args[]){
new Sample().display();
}
}输出结果
This is the static method........
如果您在eclipse中编译上述程序,则会收到警告,如下所示:
The static method display() from the type Sample should be accessed in a static way
您可以调用超类的静态方法-
使用超类的构造函数。
new SuperClass().display();
直接使用超类的名称。
SuperClass.display();
直接使用子类的名称。
SubClass.display();
以下Java示例以所有3种可能的方式调用超类的静态方法-
class SuperClass{
public static void display() {
System.out.println("This is a static method of the superclass");
}
}
public class SubClass extends SuperClass{
public static void main(String args[]){
//调用超类的静态方法
new SuperClass().display(); //superclass constructor
SuperClass.display(); //superclass name
SubClass.display(); //subclass name
}
}输出结果
This is a static method of the superclass This is a static method of the superclass This is a static method of the superclass