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. 调用父类方法:
立即学习“Java免费学习笔记(深入)”;
如果子类重写了父类方法,可以使用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 关键字的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/191359.html
微信扫一扫
支付宝扫一扫