I am in an introductory programming course and have a few months of self teaching under my belt as well, but I have yet to come across a problem where I have had to use "this." Today my teacher told our class to ALWAYS use "this" for accessing instance variables, but all of the programming I have ever done I've never used "this" to access my instance variables. Furthermore, one of the books I have says that putting "this" in front of every instance variable (no matter what) is somewhat of a sin.
For example, here is my finished code for my assignment today:
public class MyApp {
public static void main(String[] args) {
Student myStudent = new Student(101, "Tyler");
myStudent.setGrade(86.0);
myStudent.printInfo();
Student otherStudent = new Student(102, "Tom");
otherStudent.setGrade(71.0);
otherStudent.printInfo();
} //end of main
} //end of class MyApp
public class Student {
private String name;
private String grade;
private int id;
public static final int maxCourses = 5;
public Student() {
}
public Student(int id) {
this.id = id;
}
public Student(int id, String name) {
this.name = name;
this.id = id;
}
public String getName() {
return this.name;
}
public int getId() {
return this.id;
}
public String getGrade() {
return this.grade;
}
public void setName(String name) {
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public void setGrade(double mark) {
if (mark < 50.0) {
this.grade = "F";
} else if (mark < 70.0) {
this.grade = "C";
} else if (mark < 85.0) {
this.grade = "B";
} else {
this.grade = "A";
}
}
public void printInfo() {
System.out.println("Name: " + this.name);
System.out.println("ID: " + this.id);
System.out.println("Grade: " + this.grade);
System.out.println("Max Courses: " + Student.maxCourses + "\n");
}
} //end of Class Student
It is my gut reaction that this isn't a good use of the "this" keyword. Am I right in assuming that I could eliminate every "this" in the Student class simply by changing the parameter names to something other that the instance variable names? Why use it in the get and set methods? It also seems pointless to use the "this" keyword when printing the variables because different object references are invoking the print method, and therefore already know what instance variables to print.
For example:
public Student(int anId) {
id = anId;
}
So I guess what I am trying to say is why use "this" everywhere; why not just change the parameter name? Is it a matter of taste or convention to use one over the other?
To conclude, can anyone show examples where the "this" keyword is properly used; something more complex that simply getters and setters? If there are any threads I may have missed in my search, a point in the right direction would be appreciated.
Thanks

New Topic/Question
Reply




MultiQuote







|