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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值