java 关于this的问题

来源:百度知道 编辑:UC知道 时间:2024/05/15 15:16:19
以下这段代码中A句里的stu.getAge()可以替换成this.getAge()吗?为什么?

class Student {
private String school;
private int age = 16;

public String getSchool() {
return school;
}

public int getAge() {
return age;
}
}

public class MyTest{
public static void main(String[] args) {
Student stu = new Student();
System.out.println(stu.getAge());// A

}
}

你先在这里看看我的回答:
http://zhidao.baidu.com/question/44344329.html
再看看这个:
http://zhidao.baidu.com/question/44375878.html

明白了吗? 你的例子中, A句那个地方, 根本就没有this!

class Student {
private String school;
private int age = 16;

public String getSchool() {
return school;
}

public int getAge() {
return age;
}

public String toString()
{return "["+this.getAge()+"]";}
public static void main(String[] args) {
Student stu = new Student();
System.out.println(stu.toString());// A

}
}
使用THIS关键字代替对象名直接应用类定义的方法
A句中不能换成THIS

不行,this代表当前类的对象,所以,this这里应该表示的是MyTest的对象,而不是stu的

一楼的有道理。