I'm new to Java, so forgive me if it's a stupid question. I tried to find a clear answer on this forum but with no joy.
I know what 'this' is. It know it refers to an actual instance and helps narrow the context when targeting a variable, but I found that it is possible to execute the code without any issues despite not using 'this' phrase. Turns out it depends on how you name your parameters when you declare methods. As you can see below, code returns 'null' if my parameter is named the same as the state I'm initialising/modifying.
This works only in the class where the variables are declared. You'd still have to use 'this' in any sub-class, if it tried to access/modify a variable declared in its parent class.
Now, would this be considered incorrect and should it be avoided even though it seems to be working fine?
Thanks!
class Student {
protected String name;
protected int age;
protected String course;
public Student(String passName, int passAge, String course) {
name = passName;
age = passAge;
course = course; // here my parameter is named the same as the state and it will return 'null' unless we use 'this'
}
public void update(String newName, int newAge, String newCourse) {
name = newName;
age = newAge;
course = newCourse; // here I set the name of my parameter to be different and it works
}
public void display() {
System.out.println("Name: " + name + "\n Age: " + age + "\n Course: " + course + "\n");
}
public static void main(String[] args) {
Student s1 = new Student("John", 20, "Java 101");
s1.display();
s1.update("Johnny", 21, "Java 101");
s1.display();
}
}
Output:
Name: John
Age: 20
Course: null
Name: Johnny
Age: 21
Course: Java 101