繁体   English   中英

新手需要帮助理解java代码

[英]Newbie need help understanding java code

我是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();
        }
    }
} 

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 ,并且会将参数的值赋给它自己。

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

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

你为你的对象分配变量。 请记住,这些变量都在构造函数中

究其原因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来引用当前对象中的变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM