简述this在代码块中的指代作用
public class Student {
private void print(){
System.out.println(this);//输出的为地址,即(new Student)
}
public static void main(String[] args) {
Student student =new Student();//student中存储的为地址
System.out.println(student);
student.print();
}
}
该代码输出的结果相同,验证了this指代的是谁调用方法,this代表谁,此处创建的对象new Student调用了print方法,所以this指代的是student的地址,所以两者的输出结果均为student(对象)的地址。
this在实例方法中通常被省略,除非实例方法中包含与成员变量同名的局部变量时,访问成员变量需要使用this。
public static Student{
String name;
public void doHomework(){
System.out.println(this.name+"正在做作业.......");
}
}
this关键字用于调用属性、方法及本类中构造方法。
public class Student{
String name;
void doHomework(){
System.err.println(name+"正在做作业......");
}
void speak(){
new Student.doHomework;//this.doHomework
System.err.println(name+"正在说话......");
}
public static void main(String[] args) {
Student student =new Student();
student.speak();
}
}
this指代的对象如果已经赋给具体的值,则不再输出默认值
public class Student{
String name;
void doHomework(){
System.err.println(name+"正在做作业......");
}
public static void main(String[] args) {
Student student =new Student();
student.name="小哪吒";
student.doHomework();
}
}
public class Student{
String name;
void doHomework(){
name="liu"//此处省略this,引用了全局变量
System.err.println(name+"正在做作业......");
}
void speak(){
new Student.doHomework;//this.doHomework
System.err.println(name+"正在说话......");
}
public static void main(String[] args) {
Student student =new Student();
student.doHomework;
student.speak();
}
}
若代码块中将void doHomework 方法中name="liu"删去,在该方法结尾添加String name =“liu”;则结果的第一行将变为null正在做作业 。
package venus;
public class Student {
String name="Jim";
{
System.out.println(this);
System.out.println("代码块"+this.name);
}
pubilc Student (String name ){
this .name=name;//在执行这行代码之前对象已经存在,此时对象name为null;
System.out.println("构造方法"+this.name);
}
public static void main (String []args){
Student student =new Student();
System.out.println(student );
}
}
输出结果
venus.Student @52e922
代码块null
构造方法Tom
venus.Student @52e922