Java中如何调用父类中的函数(方法)?
发布时间:2023-10-07 11:53:00
Java中调用父类中的方法有两种方式:使用super关键字和使用父类的引用。
1. 使用super关键字调用父类方法:
- 在子类中使用super关键字可以调用父类中的非私有方法和属性。
- 使用super调用方法时,可以在子类中直接调用父类的方法,也可以在子类的方法中通过super调用父类的方法。
- super关键字的通用格式为:super.父类方法名(参数列表)。
示例:
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void eat() {
super.eat(); // 调用父类的eat方法
System.out.println("Dog is eating");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
}
}
输出结果为:
Animal is eating
Dog is eating
2. 使用父类的引用调用父类方法:
- 在子类中创建一个父类类型的对象,然后通过这个对象调用父类的方法。
- 父类的引用可以指向子类的对象,但通过父类的引用只能调用父类的方法,无法调用子类特有的方法。
示例:
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("Dog is eating");
}
public void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.eat(); // 调用父类的eat方法
//animal.bark(); // 编译错误,无法调用子类特有的方法
}
}
输出结果为:
Dog is eating
总结:
- 使用super关键字可以直接调用父类的方法,在子类中使用super.父类方法名(参数列表)的形式。
- 父类的引用可以指向子类的对象,通过父类的引用只能调用父类的方法。
