0

我对 java 编程语言很陌生,我真的很想帮助理解下面的代码在做什么。我对 Main 类中发生的事情有相当不错的理解。我的问题是“this._”在代码中的作用。名称究竟是如何转移的?这不是家庭作业,只是自学。练习可以在这里找到:http: //www.learnjavaonline.org/Functions另外,建议阅读会很棒!谢谢!

class Student {
    private String firstName;
    private String lastName;
    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public void printFullName(){
        System.out.println(this.firstName+" "+this.lastname);
  }
}

public class Main {
    public static void main(String[] args) {
        Student[] students = new Student[] {
            new Student("Morgan", "Freeman"),
            new Student("Brad", "Pitt"),
            new Student("Kevin", "Spacey"),
        };
        for (Student s : students) {
            s.printFullName();
        }
    }
} 
4

3 回答 3

2

this对您正在使用的对象的引用。

所以在你的样本中

class Student {
    private String firstName;
    private String lastName;
    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public void printFullName(){
        System.out.println(this.firstName+" "+this.lastname);
  }
}

this.firstNameprivate String firstName;您的对象/类中的值,
并且firstName是方法参数。

this这个例子中,它是必需的,否则它firstName = firstName会将你的参数的值分配给它自己。

于 2013-10-14T12:02:16.770 回答
0

使用的原因this是因为变量firstNamelastName被构造函数参数所遮蔽。查看与 的区别this

class Student {
    private String firstName;
    private String lastName;
    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
}

与没有相比this

class Student {
    private String myFirstName;
    private String myLastName;
    public Student(String firstName, String lastName) {
        myFirstName = firstName;
        myLastName = lastName;
}

您用于this引用当前对象中的变量。

于 2013-10-14T12:03:41.133 回答
0

看到带有“this”的变量在构造函数中。这意味着对象,所以在行中:

public Student(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;

您将变量分配给您的对象。请记住,这些变量在构造函数中!

于 2013-10-14T12:00:59.393 回答