I am asking this in response to this answer.
I'm using an example of Variable
and Var
- edit Pls note I am asking where to use Var
or Variable
:
Class NewClass {
private String Variable = "";
Public Class (String Var)
{
NewClass.Var = Variable;
}
}
OR
private String Variable = "";
Public Class (String Variable)
{
NewClass.Variable = Var; // OR WHATEVER OTHER COMBINATIONS IT MAY BE.
}
}
Which ones are the class variables, how does this differ from the parameters and which goes where?
edit
I should add, as this was in the linked answer, but it seems people haven't looked at it:
It's particularly confusing because the parameters to the function have exactly the same names as the class variables, but Patient.ptNo is not the same variable as the parameter ptNo. (Actually, Patient.ptNo should be this.ptNo, because it belongs to this particular instance of the class. Patient.ptNo would refer to a single value that's common to all objects of type Patient.)
So when people say this.Variable = Variable
I am still confused about what is what.
The class variable is the one defined by the class as a static
field, and the parameter is the one defined by the method. It's just that simple. There are also instance variables (defined at the class level but not static) and local variables (defined within a method, but not as input parameters).
public class Foo {
private static String someName; // this is a class variable
private String someOtherName; // this is an instance variable
public Foo(String anotherName) { // anotherName is a constructor parameter
int yetAnother = 1; // yetAnother is a local variable
someOtherName = "foo"; // assign a value to someOtherName
}
These two variables are completely distinct. They don't even have to have the same type! The only complication in your example is that both variables happen to have the same name. When that happens, the compiler will favor the constructor parameter (or method parameter, or local variable) over the class variable. In order to "force" it to use the class variable, you prefix it with this.
.
The thing to keep in mind is that the two variables are totally separate, regardless of their names.
So this:
class NewClass {
private String Variable = "";
Public NewClass (String Variable)
{
NewClass.Variable = Variable;
}
}
is exactly the same as this:
class NewClass {
private String Variable = "";
Public NewClass (String someOtherVariableName)
{
NewClass.Variable = someOtherVariableName;
}
}
... and it's also exactly the same as this:
class NewClass {
private String Variable = "";
Public NewClass (String Var)
{
NewClass.Variable = Var;
}
}
The convention of using the same name for a parameter as for the class variable just means you don't have to come up with pointless variants on the variable name.