在Java中,super关键字用于引用父类(超类)的一个属性、方法或构造器。在多态的上下文中,super有以下作用:
super关键字来调用父类中的原始方法。这在需要扩展子类方法的功能同时又想保留父类方法的行为时非常有用。例如:
class Animal {
void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("The dog barks");
}
void makeAnimalSound() {
super.makeSound(); // 调用父类的makeSound方法
}
}
super关键字来访问父类中的属性。例如:
class Animal {
String type = "Animal";
}
class Dog extends Animal {
String type = "Dog";
void printTypes() {
System.out.println("Type in child class: " + type); // 输出 "Type in child class: Dog"
System.out.println("Type in parent class: " + super.type); // 输出 "Type in parent class: Animal"
}
}
super()来调用父类的构造器。这可以确保父类在子类对象创建时正确地初始化其状态。如果子类的构造器没有显式地调用父类的构造器,编译器会自动插入一个对父类无参构造器的调用。例如:
class Animal {
Animal() {
System.out.println("Animal constructor called");
}
}
class Dog extends Animal {
Dog() {
super(); // 调用父类的构造器
System.out.println("Dog constructor called");
}
}
总之,在Java多态中,super关键字允许我们访问和调用父类的方法和构造器,从而实现更灵活和可扩展的代码设计。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。