九 java面向对象程序设计(this关键字)
/**
* 面向对象之四
* this关键字总结
*/
/*this关键字的第一种用法*/
//在方法中调用同类中的方法,这时的this可以省略.
class ThisPointer
{
public void function1()
{
System.out.println("function1 is calling...");
}
public void function2()
{
System.out.println("function2 is calling...");
this.function1();//调用同类中的function1;
//this是指,这个对象的function方法.
}
public void function3()
{
System.out.println("function3 is calling...");
function2();//相当于this.function2().传入的是同一个对象,所以this可以省略.
}
}
/*this关键字的第二种用法*/
//指明类中与方法参数同名的成员变量.
class Pointer
{
private int i;
private String str;
public void function(int i,String str)
{
this.i = i;
this.str = str;
//通过this,将function方法中同名的i,str和成员变量予以区分.
System.out.println("i = " + i + " , " + "str = " + str);
}
}
/*this关键字的第三种用法*/
//作为一个对象,参与到类的方法中
class Container
{
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
private Components com;
public void addComponents()//在容器中添加部件,
{
//com = new Components(new Container());
//虽然这样写没问题.但表示,在新创建一个部件的同时,又创建一个容器,然后将新部件加到新容器上.
com = new Components(this);
//用this表示这个容器类的对象,所以我们每次产生新部件是,都是加入到这个容器对象上的.
System.out.println(" is loading...");
}
}
class Components
{
private Container c;
public Components(Container c)
{
this.c = c;//部件类的构造方法指明了生产的部件是什么容器的.
System.out.print(c.getName());
}
}
/*this的第四种用法*/
//用于构造方法重载时,向上调用重载的构造方法
class Reloading
{
private int i = 0;
private String str = null;
public Reloading()
{
System.out.println(i + " " + str);
}
public Reloading(int i)
{
this();//调用了无参的构造方法.
this.i = i;
System.out.println(i + " " + str);
}
public Reloading(int i,String str)
{
this(i);//this(i)调用了带一个int类型的构造方法
this.str = str;
System.out.println(i + " " + str);
}
public String reLoadFunc(String str)
{
this.str = str;
return str;
}
public void reLoadFunc(int i,String str)
{
//this(str); //this()必须用于构造方法中.
this.i = i;
this.str = str;
System.out.println(i + " " + str);
}
}
public class ThisTest {
public static void main(String[] args) {
System.out.println("测试this的第一种用法");
ThisPointer tp = new ThisPointer();
tp.function3();
System.out.println("测试this的第二种用法");
Pointer p = new Pointer();
p.function(10, "this");
System.out.println("测试this的第三种用法");
Container c = new Container();
c.setName("box");
c.addComponents();
System.out.println("测试this的第四种用法");
new Reloading();
new Reloading(10);
new Reloading(20,"three");
System.out.println(new Reloading().reLoadFunc("four"));
new Reloading().reLoadFunc(30, "five");
}
}
/* output ~~
测试this的第一种用法
function3 is calling...
function2 is calling...
function1 is calling...
测试this的第二种用法
i = 10 , str = this
测试this的第三种用法
box is loading...
测试this的第四种用法
0 null
0 null
10 null
0 null
20 null
20 three
0 null
four
0 null
30 five
*/