【安卓学习笔记】JAVA基础Lesson8-函数的复写与super用法
发布日期:2021-05-07 20:17:06 浏览次数:14 分类:精选文章

本文共 2382 字,大约阅读时间需要 7 分钟。

Java编程中函数复写与this/super关键字的使用

在Java编程中,函数复写(Override)是面向对象编程中一个非常重要的概念。它允许子类为已有的父类方法添加新的功能或修改现有的行为。通过函数复写,子类可以更好地满足具体的需求,同时保持与父类的兼容性。

函数复写(Override)的概念

在Java中,函数复写(Override)在中文编程中也被称为“方法覆盖”或“重写”。它的核心思想是:在一个继承关系中,子类可以为与父类具有相同签名的方法定义一个新的实现。这样,子类可以在不修改父类代码的情况下,扩展或改变父类的行为。

函数复写的定义

函数复写在代码中体现为:在子类中定义与父类具有相同签名的方法。具体来说,方法的名称、参数列表以及返回类型必须与父类的方法完全一致。通过这种方式,子类可以在调用父类方法的基础上,添加自己的逻辑。

代码示例

以下是一个简单的函数复写示例:

class Lesson8_father {    String str;    int num;    void Function() {        System.out.println("the father_str is " + this.str + ", the father_num is " + this.num);    }}class Lesson8_son extends Lesson8_father {    char ch;    void Function() {        System.out.println("the son_str is " + this.str + ", the son_num is " + this.num);        System.out.println("the son_char is " + this.ch);    }}
执行结果
// 父类对象调用父类的方法Lesson8_father father = new Lesson8_father();father.str = "cba";father.num = 321;father.Function(); // 输出:the father_str is cba, the father_num is 321// 子类对象调用子类的方法Lesson8_son son = new Lesson8_son();son.str = "abc";son.num = 123;son.ch = 'C';son.Function(); // 输出:the son_str is abc, the son_num is 123// son_char is C

从上述代码可以看出,子类的Function方法在父类的基础上进行了扩展。它不仅打印了父类的属性值,还添加了子类特有的输出。

使用super调用父类的成员函数

在函数复写中,子类可以通过super关键字调用父类的方法。superthis的用法非常相似,但它们的调用对象不同。

super的作用

super关键字用于在子类方法中调用父类的方法。与this不同,super表示当前对象的父类。此外,super还可以用于调用父类的构造函数。

代码示例

以下是一个使用super关键字的函数复写示例:

class Lesson8_son extends Lesson8_father {    char ch;    void Function() {        super.Function(); // 调用父类的Function方法        System.out.println("the son_char is " + this.ch);    }}
优点

通过使用super,子类可以在不重复父类代码的前提下,扩展现有的功能。这种方式不仅代码简洁,而且有助于避免代码冗余。

this与super的区别

thissuper在Java中都用于调用类中的方法,但它们的调用对象有所不同。

  • this关键字:用于调用当前对象的方法或构造函数。this方法可以在任何位置调用任意次数。
  • super关键字:用于调用父类的方法或构造函数。super方法可以在任何位置调用,但通常在函数复写中使用。
代码示例

以下是一个使用thissuper的示例:

class Lesson8_son extends Lesson8_father {    char ch;    void Function() {        super.Function(); // 调用父类的Function方法        // System.out.println("the son_str is " + this.str + ", the son_num is" + this.num);        System.out.println("the son_char is " + this.ch);    }}
总结

在Java编程中,thissuper是非常重要的关键字。this用于引用当前对象,super用于引用父类对象。在函数复写中,super是调用父类方法的必要工具。通过合理使用super,可以实现代码的简洁与功能的扩展。

总结

  • 函数复写:允许子类为父类的方法添加新的行为,通过super调用父类的方法,可以在不重复代码的情况下扩展功能。
  • this关键字:用于引用当前对象的方法,适用于任何位置调用。
  • super关键字:用于引用父类对象的方法,常用于函数复写中,避免代码重复。

通过合理使用thissuper,可以让代码更加简洁且易于维护。在Java编程中,它们是掌握面向对象编程的核心技能。

上一篇:【安卓学习笔记】JAVA基础Lesson9-对象的转型
下一篇:【安卓学习笔记】JAVA基础Lesson7-继承

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年03月18日 14时49分45秒