什么时候可以跳过它?

oprakyz7  于 2021-07-08  发布在  Java
关注(0)|答案(3)|浏览(269)

我是java新手,所以请原谅我的问题。我试图在这个论坛上找到一个明确的答案,但毫无乐趣。
我知道这是什么。它知道它引用了一个实际的示例,并且在针对一个变量时有助于缩小上下文范围,但是我发现,尽管没有使用“this”短语,执行代码时也可以没有任何问题。结果表明,这取决于在声明方法时如何命名参数。正如您在下面看到的,如果我的参数的名称与我正在初始化/修改的状态相同,那么代码将返回“null”。
这只适用于声明变量的类。如果“this”试图访问/修改其父类中声明的变量,那么在任何子类中都必须使用它。
现在,这会被认为是不正确的吗?即使它看起来运行良好,是否应该避免?
谢谢!

class Student {

  protected String name;
  protected int age;
  protected String course;

  public Student(String passName, int passAge, String course) {
    name = passName;
    age = passAge;
    course = course;   // here my parameter is named the same as the state and it will return 'null' unless we use 'this'

  }

  public void update(String newName, int newAge, String newCourse) {
    name = newName;
    age = newAge;
    course = newCourse;   // here I set the name of my parameter to be different and it works

  }

  public void display() {
    System.out.println("Name: " + name + "\n Age: " + age + "\n Course: " + course + "\n");
  }

  public static void main(String[] args) {

    Student s1 = new Student("John", 20, "Java 101");
    s1.display();

    s1.update("Johnny", 21, "Java 101");
    s1.display();
  }
}

输出:

Name: John
 Age: 20
 Course: null

Name: Johnny
 Age: 21
 Course: Java 101
pobjuy32

pobjuy321#

如您所注意到的,如果给示例变量起的名称与构造函数参数相同,则赋值

course = course;

不初始化示例变量,因为构造函数的参数 course ,它是一个局部变量,隐藏同名的示例变量。您正在将局部变量赋给自身。
因此示例变量保持不变 null .
你得写信

this.course = course;

为了让任务生效。
另一方面,如果示例变量的名称与构造函数参数的名称不同,则可以不使用 this 前缀。
二者都

course = newCourse;

this.course = newCourse;

会很好的。
请注意,使用 this 前缀即使不是强制性的,也有发现bug的优势。
例如,如果你写错了

newCourse = course;

编译器不会抱怨,但你的 course 示例变量将不会初始化。
另一方面,如果你写错了

this.newCourse = course;

编译器将给出一个编译错误,因为 newCourse 不是示例变量。

anauzrmj

anauzrmj2#

我认为你应该读一下关于“这个”关键字的官方文件。
将this与字段一起使用this关键字最常见的原因是,字段被方法或构造函数参数隐藏。
例如,point类是这样编写的

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}

但可能是这样写的:

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

构造函数的每个参数都会隐藏对象的一个字段-在构造函数x中是构造函数第一个参数的本地副本。若要引用点字段x,构造函数必须使用此.x。
关于你的问题:
现在,这会被认为是不正确的吗?即使它看起来运行良好,是否应该避免?
这取决于你的项目或团队的代码风格。从技术上讲,这两种方法都是可行和正确的 name = newName 较短,且使用 this.name = name 更安全地避免错误。

vngu2lb8

vngu2lb83#

重要的是变量名。java总是在最接近的范围内使用变量,因此如果使用同名的参数,它将使用该参数。为了避免这种情况,您需要使用 this . 此处(删除无关代码):

public Student(String course) {
    course = course;
  }

您可以指定 course 到参数 course ,所以这个领域 course 保持不变。例如,如果您这样做:

public Student(final String course) {
    course = course;
  }

它不会编译,因为 final 关键字表示不允许将新值赋给变量(在本例中为参数 course ).
所以你需要使用 this 分配给字段。

public Student(final String course) {
    this.course = course;
  }

使用它从来不是“不正确的” this ,但您可能认为最好不要将参数命名为与字段相同的名称(如果这样做,IDE中会有一些警告要激活,以防止出现这种情况)。

相关问题