Name Clash

In my Java programming college class, we are learning more and more about classes. Specifically we are learning about access modifiers for instance variables and methods. One thing that is pretty clear is that if you have an instance variable in a class, and the variable name is myVar, then you cannot have another instance variable in the same class with the same variable name.

Within the class, you can reference an instance variable with just its name. You can optionally prepend the variable name with the keyword “this”. However in this scenario, “this” which represents the current object is already implied. So for most if not all of the time, the “this” keyword is omitted.

We are also learning about accessors and mutators in our programming class. Mutators, or setters, take an argument and set the instance variable to the value of that argument. Here is where some confusion in class came up. Support we have an instance variable in our class named “email”. What should we name the formal parameter of the setEmail method?

Most of the time, the simplest and most obvious variable name is the best one. So I thought I would name the formal argument to the mutator setEmail to be just “email”. But here is the problem and question. Does the local variable email, which is the formal parameter to the method in the class, clash with the instance variable of the same name?

The best way to answer questions like this is to try it out. It compile fine. So it must be ok. The only tricky part comes when you must set the instance variable to the formal parameter passed into the method. How do you do that if they are named the same? The trick is to qualify the instance variable with the “this” keyword. Then you get code that looks like this (no pun intended):

public void setEmail(String email)
{ = email;

Now this may not be the best practice, as there might be some ambiguity as to which variable the name email refers to. So our instructor insisted that we name the formal parameter newEmail, or something else distinct from the instance variable name. That sounds logical. It was still cool to find out you could have two variables of the same name within the class.