super关键字用于访问父类成员,解决继承中命名冲突与初始化问题:1. 访问被隐藏的父类变量(super.变量);2. 调用被重写的方法(super.方法()),实现逻辑扩展;3. 在子类构造器中调用父类构造器(super()或super(参数)),确保正确初始化。它保证了继承链中对象状态的一致性,但应避免滥用以防止紧耦合与脆弱基类问题。

super
super
super
访问父类的实例变量: 当子类中定义了一个与父类中同名的实例变量时,为了区分并访问父类的那个变量,就需要使用
super.变量名
super
class Parent {
String message = "Hello from Parent";
}
class Child extends Parent {
String message = "Hello from Child";
void displayMessage() {
System.out.println(message); // 访问子类的message
System.out.println(super.message); // 访问父类的message
}
}
// 使用示例
// Child c = new Child();
// c.displayMessage();
// 输出:
// Hello from Child
// Hello from Parent调用父类的方法: 这是
super
super.方法名()
立即学习“Java免费学习笔记(深入)”;
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
super.makeSound(); // 调用父类的makeSound方法
System.out.println("Dog barks"); // 添加狗自己的行为
}
}
// 使用示例
// Dog myDog = new Dog();
// myDog.makeSound();
// 输出:
// Animal makes a sound
// Dog barks调用父类的构造器: 在子类的构造器中,
super()
super(参数列表)
super()
super(参数)
class Vehicle {
String type;
Vehicle(String type) {
this.type = type;
System.out.println("Vehicle constructor: " + type);
}
}
class Car extends Vehicle {
String model;
Car(String type, String model) {
super(type); // 必须是第一行,调用父类的构造器
this.model = model;
System.out.println("Car constructor: " + model);
}
}
// 使用示例
// Car myCar = new Car("Sedan", "Civic");
// 输出:
// Vehicle constructor: Sedan
// Car constructor: Civic从我个人的经验来看,
super
想象一下,如果一个子类和父类都有一个名为
name
printInfo()
super
super
更深层次地讲,它保证了继承体系中对象构建的链式责任。一个子类对象的完整构造,必然依赖于其父类部分的正确构造。
super()
Object
super()
this()
区别:
this()
super()
this()
super()
联系:
this()
super()
this()
super()
this()
super()
this()
super()
this()
super()
super()
this()
理解这两者的区别和联系,对于编写清晰、高效且符合Java对象生命周期管理规范的代码至关重要。我曾见过不少新手开发者,因为混淆这两者而导致编译错误或运行时异常,究其原因,往往是对对象初始化流程缺乏深刻理解。
虽然
super
过度依赖super.method()
super.method()
super
直接通过super.field
super.field
protected
public
private
super
protected
public
getter/setter
在某些设计模式中,super
super.callbackMethod()
super
总的来说,
super
super
以上就是Java中super关键字的使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号