您的位置:首页 > 编程语言 > Java开发

【安卓学习笔记】JAVA基础Lesson8-函数的复写与super用法

2017-08-27 22:05 716 查看
1、函数的复写(override)

函数的复写(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 );
}
}

class Test{
public static void main(String args []){

Lesson8_son son = new Lesson8_son();
son.str = "abc";
son.num = 123;
son.ch  = 'C';
son.Function();

Lesson8_father father = new Lesson8_father();
father.str = "cba";
father.num = 321;
father.Function();

}
}


执行结果如下:

D:\Android\src>javac Lesson8.java

D:\Android\src>javac Test.java

D:\Android\src>java Test
the son_str is abc,the son_num is123
the son_char is C
the father_str is cba,the father_num is321

D:\Android\src>

上述代码包含含有两个类,一个是父类Lesson8_father,和一个继承Lesson8_father的子类Lesson8_son;子类除包含了父类的成员函数和成员变量之外,新定义了一个char型的成员变量ch;父类和子类都包含有定义上完全相同的成员函数Function();这就是函数的复写(override)。其中由代码可以看到这两个函数在功能却并不完全一样。子类在父类的基础上进行了补充。这也体现了函数复写的功能:对继承到的方法体进行扩展;但是现在在代码上来看:子类的代码包含了父类的代码,代码重复了。这个方法又有新的办法来解决;这个方法就是super的用法;

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

修改上述子类:
class Lesson8_son extends Lesson8_father{
char ch;

void Function(){
super.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 );
}
}


这样的结果是一样的,也达到了减少重复代码的目的,这个跟this的用法也是一致的。只是this调用的是本类的函数体,而super调用的是父类的函数体;

3、总结:
this和super的用法:

this:

this用来调用本类的成员函数和构造函数

调用构造函数使用this();并且只能使用一次,同时需要把这条语句放在本函数体的首位,传入的参数列表决定了调用哪一个构造函数;

调用成员函数使用this.xxx();可以在任意处任意条数调用。

super:

用法和this类似,区别是调用不在是本类而是父类;

By Urien 2017年8月29日 10:00:13
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐