java关键字——this

this表示对“调用方法的那个对象”的引用。它只能在方法内部使用。this的用法和其他对象引用并无不同。

一.主要用法:
     1)表示对当前对象的引用!
     2)表示用类的成员变量,而非函数参数。
     3)在构造器中调用构造器。
1)对当前对象的引用
     在java编程思想(Thinking in Jaba)中有这么一个例子:

public class Leaf{
      int i=0;
      Leaf increment(){
          i++;
          return this;
      }
       void print(){
           System.out.println("i = "+i);
       }
       public static void main(String[] args){
             Leaf x=new Leaf();
             x.increment().increment().increment().print();
       }
}
输出:i =3

   由于increment()通过this关键字返回了对当前对象的引用,所以很容易在一条语句里对同一个对象执行多次操作。

this关键字对于将当前对象传递给其他方法也很有用。

class person{
    public void eat(Apple apple){
          Apple peeled =apple.getPeeled();
          System.out.println("Yummy");
    }
}

class Peeler{
    static Apple peel(Apple apple){
         //。。。。
         return apple;
    }
}

class Apple{
     Apple getPeeled(){
           return Peeler.peel(this);
     }
}

public class PassingThis{
      public static void main(String[] args){
            new Person.eat(new Apple());
       }
}
输出:Yummy
   Apple需要调用Peeler.peel()方法,它是一个外部的工具方法,为零将其自身传递给外部方法,Apple必须使用this关键字。

2)调用类的成员变量。

public class Flower{
	int petalCount =0;
	String s="initial value";
	Flower(){
		this("hi",47);
		System.out.println("default constructor(no args)");
	}
	Flower( int petals){
		petalCount=petals;
		System.out.println("constructor int arg only,petalCount="+petalCount);
	}
	Flower( String ss){
		System.out.println("constructor String arg only,s="+ss);
	}
	Flower(String s,int petals){
		this(petals);	//调用构造方法必须放在最起始处。
		//this(s);    不能调用构造方法两次。
		this.s=s;  
		System.out.println("String &int args");
	}
	void printPetalCount(){
		//this.s(11);
		System.out.println("petalCount="+ PetalCount +" s= "+s);
	}
	public static void main(String[] args){
		Flower x=new Flower();
		x.printPetalCount();
	}
}
   在方法Flower(String s,int petals)中,形式参数和成员变量s会有冲突,所以我们可以使用this.s表示类的成员变量,而“=”后面的s则是方法中的参数,这样就可以将参数赋值给成员变量了。在java代码中经常出现这种写法。

3)构造器中调用构造器

   构造器不会的可以看这里(点击打开链接),在方法Flower(String s,int petals)中this(petals)调用构造方法,它必须放在最起始处。并且在一个构造方法中最多只能调用其他的构造方法一次,如果写两个的话,编译就会出错。




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值