java中this与super的区别

在学习java的过程中常常把this与super这个两个关键字弄混。下面来描述它们的区别。

this关键字:

                 1.引用隐式参数。

                 2.引用该类中其他的构造器。

隐式参数:该类中方法外的属性。

显示参数:该类中方法后面括号中的参数。

super关键字:

                 1.调用父类的方法。

                 2.调用父类的构造器。

下面通过简单的代码描述两者之间的区别:

package com.learn.notes;

/**
 * @ClassName ThisTest
 * @Description 描述this 的用法
 *
 * @author XingZhaohu 1178243325@qq.com
 * @date 2016-3-27 下午9:20:24
 */
 class ThisTest {
	
	private int id;//隐式参数
	private String name;//隐式参数
	
	public ThisTest(){
		System.out.println("调用无参构造器!");
	}
	
	public ThisTest(int id,String name/*显示参数*/){
		/* this 引用该类中的其他构造器*/
		this();
		
		/* this 引用隐式参数*/
		this.id = id;
		this.name = name;
		
		System.out.println("调用有参构造器!");
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThisTest test = new ThisTest(3677,"胡图图");
		/**
		 * 结果:
		 * 		调用无参构造器!
		 * 		调用有参构造器!
		 */
	}

}
package com.learn.notes;

class Animal{
	private int legs;
	private String color;
	
	public Animal(){
		
	}
	
	public Animal(int legs,String color){
		this.legs = legs;
		this.color = color;
	}
	
	public void Move(){
		System.out.println("动动动 .........");
	}
	
	public void bark(){
		System.out.println("biu biu .........");
	}
}

class Bird extends Animal{
	private int wings;
	
	public Bird(int legs,String color,int wings){
		/*super 调用父类的构造函数,必须是此方法的第一行代码!*/
		super(legs,color);
		
		this.wings = wings;
	}
	
	public void action(){
		/*super 调用父类的方法*/
		super.bark();
		super.Move();
	}
}

/**
 * @ClassName SuperTest
 * @Description Super的用法
 *
 * @author XingZhaohu 1178243325@qq.com
 * @date 2016-3-27 下午9:31:39
 */
public class SuperTest {

	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Bird bird = new Bird(2,"麻雀",2);
		bird.action();
		/**
		 * 结果:
		 * 		biu biu .........
		 * 		动动动 .........
		 */
	}

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值