在学习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 .........
* 动动动 .........
*/
}
}