首页 > 学院 > 开发设计 > 正文

函数的复写

2019-11-14 21:39:26
字体:
来源:转载
供稿:网友
函数的复写

复写(override),也叫重写、覆盖。当子类继承了父类的成员函数并需要对其函数功能进行修改时,此过程就叫复写。例子如下:

class Person{      String name;          void introduce(){           System.out.PRintln("我叫" + name);      }}

class Student extends Person{      int age;           //复写      void introduce(){           super.introduce(); //调用父类的成员函数           System.out.println("我" + age);      }}

class Test{      public static void main(String args[]){           Student s = new Student();           s.name = "zhangsan";           s.age = 18;           s.introduce();      }}

在子类中定义的函数(返回值类型、函数名和参数列表)与父类中的函数完全相同,方法体不同,这两个函数的关系就是复写。复写父类的函数时,如果只是在父类的基础上增加代码,可用super .函数名减少重复代码,并可以放在函数体内的任意行位置。

要明确复写和重载的区别。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表