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