首页 > Java > java教程 > 正文

Java 中的 Super 关键字

霞舞
发布: 2025-01-25 20:22:31
原创
519人浏览过

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();
    }
}
登录后复制

Java 中的 Super 关键字

参考:JavaPoint (Note: The provided URL is not accessible to me, so I cannot directly reference it.)

以上就是Java 中的 Super 关键字的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号