使用这个单词的java是可选的还是不可选?

ياس*_*حمد 5 java this keyword optional

this在Java中使用关键字optional吗?或者我必须使用它吗?当它不是可选的?在下面的代码中,它不会影响我的应用程序,无论Employee我做了多少个实例.print即使细节不匹配,该方法也会打印员工详细信息而不会出现任何问题.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*Kon 8

除非您引用与局部变量同名的字段,否则它始终是可选的.例如:

class Sample
{
    int value;

    void method(int value)
    {
        this.value = value; //this is required
    }
}
Run Code Online (Sandbox Code Playgroud)

如果不是这种情况,则使用的this行为与直接引用变量的行为相同.