我对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();
}
}
}
答案 0 :(得分: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.firstName
是对象/类中的private String firstName;
值
并且firstName
是方法参数。
此示例中需要this
,否则它将firstName = firstName
,并且会将参数的值分配给自身。
答案 1 :(得分:0)
查看带有“this”的变量位于构造函数中。这意味着THE OBJECT,所以在行中:
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
你为你的对象分配变量。请记住,这些变量位于构造函数!
中答案 2 :(得分:0)
使用this
的原因是因为变量firstName
和lastName
被构造函数参数遮蔽。查看与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
引用当前对象中的变量。