java this 用法

来源:百度知道 编辑:UC知道 时间:2024/05/27 20:06:54
我看到一句
classic Apple {
Apple getPeeled(){return Peeler.peel(this);
这里的this代表 Apple对吧 为什么直接写 Apple

呵呵,java编程思想上的一小段代码。

this可以看做是一个变量,它的值是当前对象的引用。本身peel(Apple apple)这个方法调用的时候需要一个形式参数,就是一个Apple对象,所以要传给它一个apple对象。

书上的写法有点绕,只是想你明白this这个关键字,如果你这样做:
Apple a=new Apple(); 那么程序就可以这样写了:

classic Apple {
Apple getPeeled(){return Peeler.peel(a);

这样很明显看出,this就是代表了一个Apple类的对象。

一般来说,this关键字用来处理成员变量和参数重名的情况。例如:
class Example
{
private String name; //成员变量只能用类的对象去使用
void setName(String name)
{
//this.name表示是成员变量,把形式参数name的值传给成员变量
this.name=name;
}
}

这里的this代表 Apple的某个对象,所以不能写成Apple.(这回答是有问题的,你就将就吧)

是,但不能写Apple,要写
New Apple()

this代表 Apple 这个类new出来的一个对象!
直接 Apple肯定不行 ,因为要使用它 必须利用这个类来创建一个对象才能使用