super和this

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

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值