java super关键字详解:访问父类成员和构造器
Java中的super关键字是一个引用变量,用于引用直接父类对象。 当创建子类实例时,会隐式创建父类实例,并由super引用。super主要用于以下三种场景:
1. 访问父类成员变量:
如果父类和子类拥有同名成员变量,可以使用super关键字区分访问父类变量。
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();
}
}
2. 调用父类方法:
如果子类重写了父类方法,可以使用super关键字调用父类方法。
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();
}
}
3. 调用父类构造器:
super()用于调用父类的构造器。 子类构造器中,第一行语句通常是super()或this(),用于调用父类构造器或本类其他构造器。如果没有显式调用,编译器会隐式添加super()调用父类的无参构造器。
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();
}
}
super关键字的实际应用示例:
以下示例展示了如何使用super关键字在子类构造器中调用父类构造器,实现代码复用。
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();
}
}
参考:JavaPoint (Note: The provided URL is not accessible to me, so I cannot directly reference it.)
以上就是Java 中的 Super 关键字的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论