方法法重写复写(override)是什么?为什么用?
- Override的目的:
- 对父类中不适合子类的函数进行修改
- 怎么样称之为复写?:
- 1.在父子关系的两个类中
- 2.两个类中有各有一个函数,定义一样(返回值,函数名,参数列表)
怎么Oerride?
- 在子类中定义一个与父类中函数定义一样(返回值,函数名,参数列表)的函数即可
- 与重载区别:
- 重载是在一个类里面,而复写在有继承关系的两个类中。
- 重载为多个函数参数列表不一样,复写函数定义要与父类中的一模一样。
如何利用super?
- super针对于继承关系的类中
- super可以调用父类的构造器,也可用调用父类的方法
- 调用方法:super.构造器(参数列表) super.父类的函数(参数列表)
示例.
1用函数复写父类方法,还有用super调用父类方法
//复写函数,super调用父类函数 class Father{ String name; int age; Father(String name,int age){ this.name=name; this.age=age; } void introduce(){ System.out.println("你好 我的名字叫 "+name+" 我的年龄 "+age); } void say(String word){ System.out.println(word); } } class Son extends Father{ String address; //构造函数初始化 Son(String name,int age,String address){ super(name,age); this.address=address; } //重写父类的introduce函数,重写要求返回值,函数名,参数列表都一样 void introduce(){ //System.out.println("你好 我的名字叫 "+name+" 我的年龄 "+age);//对比父类,这条是重复代码 say("------用super调用父类方法--------"); //1.用super调用父类的方法 super.introduce(); System.out.println("我家住在 "+address); } } public class Test{ public static void main(String[] agrs){ //创建Son 的对象 Son yanggan=new Son("yanggan",21,"百色"); yanggan.introduce(); } /*输出: ------用super调用父类方法-------- 你好 我的名字叫 yanggan 我的年龄 21 我家住在 百色 */ }
作者:YangGan
本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名Yanggan(包含链接).