ilndboi
ilndboi

Reputation: 39

Newbie need help understanding java code

I'm very new to the java programming language and I would really like some help understanding what the following code is doing. I have a pretty decent understanding of what is going on within the Main class. My problem is what part "this._" plays within the code. How exactly are the names getting transferred? This is not homework just self study. The exercise can be found here:http://www.learnjavaonline.org/Functions Also, suggested reading would be great! Thanks!

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

Upvotes: 0

Views: 348

Answers (3)

Scott Helme
Scott Helme

Reputation: 4799

The reason this is used is because the variables firstName and lastName are shadowed by the constructor parameters. See the differences with this:

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

Compared to without this:

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

You use this to reference variables in the current object.

Upvotes: 0

Dodge
Dodge

Reputation: 8307

this references to the object your is working in.

so in your sample

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 is the private String firstName; value in your object/class
and firstName is the method parameter.

the this is required in this example as it otherwise would be firstName = firstName and that would assign the value of your parameter to itself.

Upvotes: 2

Tomasz Waszczyk
Tomasz Waszczyk

Reputation: 3139

See that variables with "this" are in constructor. This means THE OBJECT, so in the lines:

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

you assing variable to your object. Remember that these variables are in constructor !

Upvotes: 0

Related Questions