`
stinge
  • 浏览: 149326 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

super 与 this

    博客分类:
  • java
 
阅读更多

super 与 this

 

1、 构造函数内使用this() 和super()

    this()来调用同一类内的其他构造函数,必须放在第一行

    super()从子类的构造函数调用其父类的构造函数,必须放在第一行。

     可以根据参数的不同选择调用不同的构造函数。

2、this 当局部变量与成员变量重名时,使用this访问成员变量

    super 子类内调用父类成员   super.成员变量或super.成员函数

 

3、举例

 

package com;
public class JavaTest {
public static void main(String ar[])
{
	TChild tc = new TChild();
}
}

class TFather{
	protected int num;
	public TFather(){
		System.out.println("父类无参构造函数");
	}
	public TFather(int n){
		//调用TFather()
		this();
		int num = n;
		//当成员变量与局部变量同名时,使用this访问成员变量
		System.out.println("局部变量num "+num);
		System.out.println("成员变量num "+this.num);
		System.out.println("父类有参构造函数");
	}
	public void show(){
		System.out.println("父类show");
	}
}
class TChild extends TFather{
	protected int num;
	public TChild(){
		//默认调用TFather(),super()有参数时调用TFather(int n)
		super(1);
		show();
		super.num = 232;
		System.out.println("父类变量num "+super.num);
		//调用父类方法
        super.show();
	}
	public void show(){
		System.out.println("子类show");
	}
}
 

 

  结果:

 

父类无参构造函数
局部变量num 1
成员变量num 0
父类有参构造函数
子类show
父类变量num 232
父类show
 

 

 

 

 

 

 

 

 

分享到:
评论
1 楼 Will.Du 2011-12-09  
挺好的,不过你的层数太少,如果是extends了两次,那么super调用情况如何没有体现出来~~

相关推荐

Global site tag (gtag.js) - Google Analytics