0
package holinheritation2;

import java.util.Scanner;

public class Inheritation2 {

    public static void main (String args[]) {

        Animal wolf = new Animal();
        Scanner scanner = new Scanner(System.in);
        String name = scanner.next();
        wolf.setName(name);

        if (wolf.getName().equalsIgnoreCase("Kobe")) {
            System.out.println("You are a wolf called Kobe!");
        }
    }

}

package holinheritation2;

import java.util.Scanner;

public class Animal {

    private String name;
    private int age;

    public void setName(String name) {
        this.name = name;  
    }
    public String getName() {
        return this.name;
    }

`enter code here`}

What is the purpose of writing this.name = name and is there any difference if I return "name" instead of "this.name" on the getName method? I think I understand this.name = name however clarification is appreciated.

Rarblack
  • 4,559
  • 4
  • 22
  • 33
Marquette
  • 1
  • 2

4 Answers4

1

The name refers to the local variable name defined within the method. The this.name refers to the variable set in the class.

This is used in order the compiler to be able to distinguish variables set with the same name.

Sir. Hedgehog
  • 1,260
  • 3
  • 17
  • 40
0

What is the purpose of writing "this.name = name"

I assume you mean in setName. In setName, this.name is your instance variable ("field"), and name is the parameter setName accepts. So this.name = name sets the instance field's value using the parameter's value.

is there any difference if I return "name" instead of "this.name" on the getName method?

No, because there isn't any name parameter or local variable in scope in getName, so the Java compiler knows you mean the name instance variable. (Always including this even when it's not needed, or not using it when it's not needed, is a style choice.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

This is done when there is shadowing, You have name variable declared twice, one within method as parameter or local variable, other as member of class, within the method variable member is shadowed by parameter variable name, so to access it you have to specify this.name which refers to the member variable name.

Hence within the method name variable refers to the parameter where as this.name refers to the member variable name. so shadowing is resolved.

private String name;

public void setName(String name) {
    this.name = name;  
}
The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
0

If the local variable has the same name as the instance variable, then then the local variable will hide the instance variable and you have to use "this" keyword in order to access the hidden instance variable.