【发布时间】:2015-03-09 15:02:04
【问题描述】:
在 Java 中是否使用关键字 this 可选?还是我必须使用它?当它不是可选的?
在以下代码中,无论我创建了多少 Employee 实例,它都不会影响我的应用程序。
print 方法打印 Employee 详细信息没有任何错误,即使详细信息不匹配。
public class Employee {
String name;
int Salary;
int pension;
String workPlace;
String teleNo;
int age;
void printDetails(){
System.out.println("Name is : "+this.name );
System.out.println("age is : "+this.age );
System.out.println("WorkPlace is : "+this.workPlace );
System.out.println("Salary is : "+Salary );
System.out.println("Pension is : "+this.pension );
System.out.println("Telephone No. is : "+this.teleNo );
System.out.println("age is : "+Integer.toString(age) );
}
}
public class Main extends Employee {
/**
* @param args
*/
public static void main(String[] args) {
Employee obj=new Employee();
obj.age=25;
obj.name="Yasser";
obj.pension=100_000;
obj.teleNo="xxx_xxxx";
obj.workPlace="Egypt";
obj.Salary=1000000;
obj.printDetails();
Employee obj1=new Employee();
obj1.age=29;
obj1.name="asser";
obj1.pension=100_000;
obj1.teleNo="xxx_xxxx";
obj1.workPlace="rgypt";
obj1.Salary=2000000;
obj1.printDetails();
}
}
【问题讨论】:
-
您可以通过谷歌搜索轻松找到更多信息:docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
-
this总是指类的当前实例。所以你不需要使用,除非有一个同名的方法局部变量,但你想使用你的实例变量,然后我们显式在变量名前加上this,告诉编译器我们需要使用实例变量而不是在这种情况下是一个局部变量
标签: java this keyword optional