this和super的区别
No. | 区别 | this | super |
1 | 操作属性 | this.属性:表示调用本类中的属性,如果本类中的属性不存在,则从父类查找 | super.属性:表示调用父类中的属性 |
2 | 操作方法 | this.方法():表示调用本类中的方法,如果本类中的方法不存在,则从父类查找 | super.方法():表示调用父类中的方法 |
3 | 调用构造 | this()调用本类中的其他构造方法 | super():由子类调用父类中的构造方法 |
4 | 查找范围 | 先从子类中查找,如果没有从父类中查找 | 不查子类直接查找父类 |
5 | 特殊 | 当前对象 | - |
super()子类调用父类构造方法,每子类构造方法第1行(若没有在构造方法里调用super(),则会默认调用无参super()),因若想实例化子类对象,则必须先实例化其父类对象.
package extend;
/**
* the parent class
* @author yangfei
* @since 2014-3-31
*/
public class Person {
public Person(){
System.out.println("this is a person");
}
public Person(String name){
System.out.println("this is a person,his name is "+name);
}
public Person(String name,int age){
System.out.println("this is a person,his name is "+name+" and his age is "+age);
}
public void print(){
System.out.println("print person");
}
}
子类代码
package extend;
/**
* @author yangfei
* @since 2014-3-31
*/
public class Chinese extends Person{
/**
*
*/
public Chinese() {
//super();
System.out.println("this is a chinese");
}
/**
* @param name
* @param age
*/
public Chinese(String name, int age) {
//super(name, age);
System.out.println("this is a chinese,his name is "+name+" and his age is "+age);
}
/**
* @param name
*/
public Chinese(String name) {
//super(name);
System.out.println("this is a chinese,his name is "+name);
}
public void print(){
super.print();
System.out.println("in Chinese");
System.out.println(super.getClass().getCanonicalName());
}
public static void main(String args[]){
Chinese chinese1 = new Chinese("yangfei");
chinese1.print();
}
}
运行结果
this is a person
this is a chinese,his name is yangfei
print person
in Chinese
extend.Chinese
测试证明:
1.在构造函数中若不显式的调用super(),系统会默认调用父类的无参构造函数。
2.super.getClass().getCanonicalName()返回的是当前类的名称,这个请参考http://blog.csdn.net/sujudz/article/details/8034770