在 Java 中,能否从子类调用超类的静态方法?
静态方法是可以无需实例化类即可调用的方法。如果要调用超类的静态方法,可以直接使用类名来调用它。
示例
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 示例以所有三种可能的方式调用超类的静态方法:
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[]){
//Calling static method of the superclass
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP