Java 中,我们可以从子类调用超类的静态方法吗?
java 8object oriented programmingprogramming
静态方法是无需实例化类即可调用的方法。如果要调用超类的静态方法,可以使用类名直接调用。
示例
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 中编译上述程序,您将收到警告,提示为 −
警告
应以静态方式访问类型 Sample 中的静态方法 display()
调用超类的静态方法
您可以调用超类的静态方法 −
- 使用超类的构造函数。
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.display(); //超类名称 SubClass.display(); //子类名称 } }
输出
This is a static method of the superclass This is a static method of the superclass This is a static method of the superclass