java super关键字详解:访问父类成员和构造器
Java中的super关键字是一个引用变量,用于引用直接父类对象。 当创建子类实例时,会隐式创建父类实例,并由super引用。super主要用于以下三种场景:
1. 访问父类成员变量:
如果父类和子类拥有同名成员变量,可以使用super关键字区分访问父类变量。
<code class="java">class Animal {
String color = "white";
}
class Dog extends Animal {
String color = "black";
void printColor() {
System.out.println(color); // 输出子类变量:black
System.out.println(super.color); // 输出父类变量:white
}
}
public class TestSuper1 {
public static void main(String[] args) {
Dog d = new Dog();
d.printColor();
}
}</code>2. 调用父类方法:
立即学习“Java免费学习笔记(深入)”;
如果子类重写了父类方法,可以使用super关键字调用父类方法。
<code class="java">class Animal {
void eat() {
System.out.println("Animal is eating...");
}
}
class Dog extends Animal {
void eat() {
System.out.println("Dog is eating bread...");
}
void work() {
super.eat(); // 调用父类eat()方法
bark();
}
void bark() {
System.out.println("Dog is barking...");
}
}
public class TestSuper2 {
public static void main(String[] args) {
Dog d = new Dog();
d.work();
}
}</code>3. 调用父类构造器:
super()用于调用父类的构造器。 子类构造器中,第一行语句通常是super()或this(),用于调用父类构造器或本类其他构造器。如果没有显式调用,编译器会隐式添加super()调用父类的无参构造器。
<code class="java">class Animal {
Animal() {
System.out.println("Animal created");
}
}
class Dog extends Animal {
Dog() {
super(); // 调用父类构造器
System.out.println("Dog created");
}
}
public class TestSuper3 {
public static void main(String[] args) {
Dog d = new Dog();
}
}</code>super关键字的实际应用示例:
以下示例展示了如何使用super关键字在子类构造器中调用父类构造器,实现代码复用。
<code class="java">class Person {
int id;
String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
class Emp extends Person {
float salary;
Emp(int id, String name, float salary) {
super(id, name); // 调用父类构造器初始化id和name
this.salary = salary;
}
void display() {
System.out.println(id + " " + name + " " + salary);
}
}
public class TestSuper5 {
public static void main(String[] args) {
Emp e1 = new Emp(1, "Ankit", 45000f);
e1.display();
}
}</code>
参考:JavaPoint (Note: The provided URL is not accessible to me, so I cannot directly reference it.)
以上就是Java 中的 Super 关键字的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号