我们可以在 Java 中从静态方法调用超类的函数吗?
继承可以定义为一个(父/超)类获取另一个(子/从)类的属性(方法和字段)的过程。通过使用继承,可以按层次结构对信息进行管理。继承属性的类称为子类,而其属性被继承的类称为超类。简而言之,在继承中,可以使用子类的对象访问超类的成员(变量和方法)。
示例
class SuperClass {
public void display(){
System.out.println("Hello this is the method of the superclass");
}
}
public class SubClass extends SuperClass {
public void greet(){
System.out.println("Hello this is the method of the subclass");
}
public static void main(String args[]){
SubClass obj = new SubClass();
obj.display();
obj.greet();
}
}输出
Hello this is the method of the superclass Hello this is the method of the subclass
从静态上下文中调用超类方法
是的,您可以从子类的静态方法调用超类的方法(使用子类的对象或超类的对象)。
示例
class SuperClass{
public 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 methods of the superclass
new SuperClass().display(); //superclass constructor
new SubClass().display(); //subclass constructor
}
}输出
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