------- android培训、java培训、期待与您交流! ----------
举个例说明:
public class Test extends Test1
{
Test(int i,String str)
{
super(i,str); //用父类的构造函数初始化
}
public static void main(String[] args)
{
Test1 ts0=new Test1(2);
Test1 ts1=new Test1("Good!");
Test1 ts2=new Test1(520,"Yeah Good!");
//ts0.increment()返回一个在ts0基础上i++的Test1对象,接着又返回在上面返回的对象基础上i++的Test1对象
System.out.println("Test1 i = "+ts0.increment().increment().increment().i);
Test tss = new Test(920,"Good!");
System.out.println("Test i = "+tss.increment().increment().increment().increment().i); //是用父类的方法给变量赋值
}
}
class Test1
{
int i;
Test1(int i) //第一个构造器:有一个int型形式参数
{
this.i=i+1; //此时this表示引用成员变量i,而非函数参数i
System.out.println("Int constructor i——this.i: "+i+"——"+this.i);
System.out.println("i-1:"+(i-1)+",this.i+1:"+(this.i+1)); //两个输出结果证明了i和this.i是不一样
}
Test1(String s) //第二个构造器:有一个String型形式参数
{
System.out.println("String constructor:"+s);
}
Test1(int i,String s) //第三个构造器:有一个int型形参和一个String型形式参数
{
this(s); //this调用第二个构造器
//this(i);
//此处不能用,因为其他任何方法都不能调用构造器,只有构造方法能调用它
//注意:就算是构造方法调用构造器,也必须位于构造函数的第一行,构造方法也只能调用一个且仅一次构造器
this.i=i++; //this以引用该类的成员变量
System.out.println("Int constructor:"+i+",String constructor:"+s);
}
public Test1 increment()
{
this.i++;
return this; //返回的是当前的对象,该对象属于(Test1)
}
}
运算结果如下:
C:\Users\lenovo\Desktop>javac Test.java
C:\Users\lenovo\Desktop>java Test
Int constructor i——this.i: 2——3
i-1:1,this.i+1:4
String constructor:Good!
String constructor:Yeah Good!
Int constructor:521,String constructor:Yeah Good!
Test1 i = 6
String constructor:Good!
Int constructor:921,String constructor:Good!
Test i = 924
从这个例子中可以看出,this的作用有普通的直接引用、方法中的某个形参名与当前对象的某个成员有相同的名字.为了不混淆,使用this区分有this引用的是成员,没有this是形式参数、引用构造函数,super用在构造函数时要放在第一行,相当于调用super就刷新了构造函数, 还可以用来调用的父类的成员,它引用当前对象的直接父类中的成员(用来访问直接父类中被隐藏的父类中的成员数据或函数,也就是基类与派生类中有相同成员定义时的调用)
super和this的异同:
1、super(参数):调用父类的构造方法 。
2、this(参数):调用本类的其他构造方法。
3、都必须放在构造方法的第一行。
4、super:引用父类中的成员,当子类和父类中的成员(变量、方法)重名时,就用super。
5、this:代表当前对象名(在程序中易产生二义性之处,应使用this来指明当前对象,如果函数的形式参数与类中的成员数据同名,这时需用this来指明成员变量名)。
6、this()和super()都指的是对象,所以,均不能在static中使用。包括:static变量,static方法,static语句块。
7、从本质上讲,this是一个指向本对象的指针, 然而super是一个Java关键字。