函数的复写

1. 函数的复写(override)

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

 

1. 函数的复写

    修改父类中成员函数, 就叫复写

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

    this()就可调用本类的构造函数, this.函数名 即可调用本类的成员函数

    super()可调用父类的构造函数, super.函数名 即可调用父类的成员函数

    override语法特征:<1>在具有父子关系的两个类中

                             <2>父类和子类各有一个函数, 函数的定义(返回值类型、函数名和参数列表)完全相同

    Eg. 

 

1 class Person{
2     int age ;
3     String name ;
4     void introduce(){
5         System.out.println("我的名字是" + this.name + ",我的年龄是" + this.age);        
6     } 
7 }

 

 

1 class Student extends Person{
2     String address ;
3     
4     void introduce(){
5         System.out.println("我的名字是" + this.name + ",我的年龄是" + this.age);    
6         System.out.println("我的家在" + this.address);
7     } 
8 }
1 class Test{
2     public static void main(String args []){
3         Student student = new Student();
4         student.age = 10 ;
5         student.name = "张三" ;
6         student.address = "北京";
7         student.introduce();
8     }
9 }

         Tips : javac *.java可编译当前目录中所有java文件 

             

 

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

      上述代码中, Student有重复代码, 修改如下

     

1 class Student extends Person{
2     String address ;
3     
4     void introduce(){
5         super.introduce();
6         System.out.println("我的家在" + this.address);
7     } 
8 }

     

 

posted @ 2014-05-19 09:28  Mirrorhanman  阅读(223)  评论(0编辑  收藏  举报