Reputation: 8015
With respect to the following class definition:
public final class ConfigComparer {
...some code ....
public ConfigComparer(String defaultFile, String siteFile)
throws NoSuchFieldException, IllegalAccessException {
this.defaultFile = defaultFile;
this.siteFile = siteFile;
defaultConfig = loadConfiguration(defaultFile);
siteConfig = loadConfiguration(siteFile);
load();
}
..... some code ....
}
Inside the constructor ConfigComparer
, there are this.defaultFile = defaultFile;
and this.siteFile = siteFile;
what are these two this.
used for or what are their design considerations?
Upvotes: 2
Views: 68
Reputation: 4194
The class definition should be something like this:
public final class ConfigComparer {
private String defaultFile;
private String siteFile;
...some code ....
}
And, in the constructor, you are assigning the parameters (String defaultFile, String siteFile)
to those attributes. Note that if the attributes would have a different name this is not required, but in this case it it, if not then you are assigning to the parameters their same value.
Upvotes: 0
Reputation: 11487
As per the link, this
refers to Within an instance method or a constructor, this is a reference to the current object
Your code constructor can be written without this
keyword
like
public ConfigComparer(String defaultFile, String siteFile)
throws NoSuchFieldException, IllegalAccessException {
instance_defaultFile = defaultFile;
instance_siteFile = siteFile;
defaultConfig = loadConfiguration(defaultFile);
siteConfig = loadConfiguration(siteFile);
load();
}
In your constructor, the keyword this
is necessary since both your instance variable
and your method parameter
are the same, the jvm needs to know what you are referring to and thats why you need to say
this.defaultFile = defaultFile
Upvotes: 0
Reputation: 7796
this
refers to the instance/object that your code is running inside.
this.defaultFile
references the instance variable defaultFile
of the class ConfigComparer
.
defaultFile
references the variable passed into the constructor.
When this
is not specified, it always looks for local variables, before instance variables.
Upvotes: 3
Reputation: 1725
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor
by using this
.
From within a constructor, this
keyword to call another constructor
in the same class. Doing so is called an explicit constructor invocation.
Source: http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Upvotes: 0