继承可以定义为一个(父/父)类获取另一个(子/子)属性(方法和字段)的过程。通过使用继承,信息可以按层次结构顺序进行管理。继承属性的类称为子类,其属性被继承的类称为超类。简而言之,在继承中,您可以使用子类对象访问超类的成员(变量和方法)。
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[]){
//超类的调用方法
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