I have seen accessor methods using this and ones that don't. Do they produce the same results?
For example:
public setName(string name){
this.name=name;
}
public setName(string n){
name=n;
}
public void getName{
return name;
}
public void getName{
// is "this" here useless?
return this.name;
}
What are the differences? Which way is better?
You need to use this when you want to reference the class level variable which has the same name as the local variable in the method. It is only required when the variables have the same name. You can always use this if you want, but it isn't necessary. And the difference between
this.s = s;
and
s = myString;
is just a style preference, and not a big important one that wars are fought over.
Yes, they are entirely equivalent in their function and resulting bytecode (afaik).
The ’this’ keyword is only used when referencing an instance variable (a non-static variable that is defined with the class or relevant super-classes), in order to differentiate it from a local variable of the same name. Omitting the ’this’ keyword in such a situation would assign the local variable to itself.
Regarding your edit about what is better, some prefer not naming variables the same, but some like using ’this’ to explicitly refer to an instance variable. It comes down to a matter of taste and readability.
It is the same.
If your method has a variable with the same name of a class field (eg "name") you need to write "this.name" to refer to class field, because writing only "name" you are refering to method variable.
So in the second example you wrote, you have two different names ("name" and "n") and you don't need to write "this.name".
By the way, in the second example, you are free to say "this.name" if you want, but it is not mandatory... (in my opinion it is not mandatory, but it is a great way to make your code more easy to read).
At the end choose what method you prefer.
In my mind the first one is a more "elegant" way to write code.
Related
I was wondering if it's possible to use a variable of a java class in another java class.Suppose variable Time is defined and calculated in Class A, how can I use it in Class B?
Other answers have suggested increasing a variable's visibility. Don't do this. It breaks encapsulation: the fact that your class uses a field to store a particular piece of information is an implementation detail; you should expose relevant information via the class's API (its methods) instead. You should make fields private in almost all cases.
Likewise, some other answers have suggested possibly making the variable static. Don't do this arbitrarily. You need to understand what static really means: it's saying that this piece of information is related to the type rather than to any one particular instance of the type. Occasionally that's appropriate, but it's generally a road towards less testable code - and in many cases it's clearly wrong. For example, a Person class may well have a name variable, but that certainly shouldn't be static - it's clearly a piece of information about a single person.
You should think carefully before exposing information anyway - consider whether there's a wider operation which the class in question could expose, instead of just giving away its data piecemeal - but when you do want to expose a field's value, use a property. For example:
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
By exposing it via a method, you can later change the implementation details without breaking existing clients.
Then from another class, you'd just call the getName() method:
// However you end up getting a reference to an instance of Person
Person person = ...;
String name = person.getName();
If you do have a static field, you can expose the value in the same way, but with a static method, which you'd call using the class name.
Be careful about returning values which are mutable, e.g. java.util.Date. This is another reason for using a getter method instead of allowing direct access to the field - you can make the method return a defensive copy where you need to.
If it is declared as public, you may use ClassA.yourVariable. On the other hand, for private access modifier, include the getter to your ClassA. On the ClassB, call ClassA.getYourVariable().
Also read about access specifiers in Java it might help.
If the variable is static, you can refer to it as A.Time from any code that has access to the variable. There's only one Time value for all of class A. If it is an instance variable, and you have an instance a of class A, you can refer to the variable as a.Time. There's a separate value for each instance of class A.
This is subject to Java's access rules:
if the field is public, any code can access it (this makes public variables kind of dangerous unless they are also declared final)
if the field is protected, only code in the same package or in a subclass of A can access it
if the field has default access, only code in the same package as class A can access it
if the field is private, only code in class A (including inner classes of A) can access it.
Alternatively, you can provide an accessor method in class A:
public class A {
. . .
public class getTime() {
return this.Time; // the "this." is optional
}
}
If you declare your Variable as public or static you will be able to access it from another class.
WHICH IS A VERY VERY BAD IDEA :)
I have an IDE which I can use to automatically create constructors and setters for instance variables, but I was wondering if the way that it creates them is possibly not best practice. Here is what it does:
private String partNum;
private String partDesc;
private int quant;
private double price;
public Invoice( String partNum, String partDesc, int quant, double price )
{
this.partNum = partNum;
this.partDesc = partDesc;
this.quant = quant;
this.price = price;
}
It's the 'this.name' thing that I'm worried about, as well as the constructor labeling the parameters the same names as the variables it's constructing. The setter also does the same thing -- uses a parameter name that's the same as the name of the variable it's setting, and uses this.name.
So, is there anything wrong with this?
That is my preferred way. Otherwise, you would have to think of different arbitrary names for the input parameters and that turns into a hassle.
What you are witnessing is pretty standard Java practice, and is even mentioned in the Java Language Specification:
If a name declared as a local variable is already declared as a field
name, then that outer declaration is shadowed (§6.3.1) throughout the
scope of the local variable. Similarly, if a name is already declared
as a variable or parameter name, then that outer declaration is
shadowed throughout the scope of the local variable (provided that the
shadowing does not cause a compile-time error under the rules of
§14.4.2). The shadowed name can sometimes be accessed using an
appropriately qualified name.
For example, the keyword this can be used to access a shadowed field
x, using the form this.x. Indeed, this idiom typically appears in
constructors (§8.8):
class Pair {
Object first, second;
public Pair(Object first, Object second) {
this.first = first;
this.second = second;
}
}
In this example, the constructor takes parameters having the same
names as the fields to be initialized. This is simpler than having to
invent different names for the parameters and is not too confusing in
this stylized context. In general, however, it is considered poor
style to have local variables with the same names as fields.
When local variables to a method have the same name as class variables, they effectively 'shadow' or hide those variables. But you can still access the class variables by referring to them via the this context scope.
No. that is not at all a problem. These are just variable names. The lvalue and rvalue are going to maintain their uniqueness.
No there's nothing wrong. The this keyword resolve the ambiguity because it tells the compiler that the l-value you are setting is the member variable(es. this.partNum) and not the input parameter(partNum).
If this is a bad practice, that's more a matter of personal taste. Some people don't like to use the same name for both the member variable and the input parameter. Personally I've use this often for several reasons:
avoid proliferating of names
Eclipse start autocompleting the name if it starts with "this." :)
So I have a simple programming question that I can't seem to find the answer for. While browsing some code from Google I noticed that they put 'this' in front of a lot of methods in their code. What is the purpose of doing this? Does it have any benefits over not using it?
An example:
this.doMethod();
Compared to:
doMethod();
I'm sure its a simple answer, I just like being able to understand all of the code that I read.
No, it makes no difference at all for method calls. Use whichever you find more readable.
Note that it does make a difference when disambiguating between instance variables and parameters (or other local variables though). For example:
public void setFoo(int foo) {
this.foo = foo;
}
That's assigning the instance variable a value from the parameter - just using foo = foo; would be a no-op.
this represents the object instance of the current class. In programming practice, most of the time, it is used to break the ambiguity. e.g. in example, there is a class variable named name and method parameter named named, so this is used to differentiate the two.
public void setName(String name){
this.name= name;
}
If you don't have any ambiguity then it doesn't create much difference i.e. setName("John"); and this.setName("John"); is same thing. But still there is one difference. this.setName("John"); follows the same pattern as you are calling the method on objects(e.g. emp.setName("A");); here this representing the sane class object.
There is no difference between them at all. You always call a method on some reference. If you don't use any reference, this reference is implicit.
So, doMethod() is same as this.doMethod(). By using this, you just make it explicit.
One place where it is required to use this reference explicitly is the place where you are assigning the value of method/constructor parameter to the instance variable, and both have same name, as in the below example:
public Demo(int var) { // Constructor
this.var = var;
}
So, in the above example, this.var refers to instance variable and is different from var, which refers to constructor parameter.
Hi apologies for the basic question, im sure I've been told the answer before and I've spent some time searching but couldn't find a good answer (probably because its hard to phrase as a search query), I've done a little bit of OO programming before but ive done a lot of procedural stuff recently so that seems to be clouding my thoughts.
I have a program that has to work with strings, part of that program involves sanitising a string, so I have this method:
private void sanitizeString() {
removeEscape();
removePunctuation();
removeCaps();
}
And earlier in the class declared the variable
String x = "... some string ..."
In procedural you would obviously pass all of the functions the string that they need to work on, my question is in OO is it ok to have this string declared at the top of the class and then just do something like
private void removeCaps() {
x = x.toLowerCase();
}
or should it be
private String removeCaps(String y) {
y = y.toLowerCase();
return y;
}
I think this it should be the first way, and I know that that works ok, but im doing something that has to demonstrate good OO so I just want to check I have my basic assumptions right.
Thanks
You have a trade off here:
Declaring the variable as a class variable means that you must create a new object for each String you want to sanitize.
Passing the String variable to each method means that you can reuse the same object to sanitize multiple Strings.
You must weigh the advantages and disadvantages of each approach to decide which is most appropriate for your particular situation.
Since x is declared as class variable, this one is fine:
private void removeCaps() {
x = x.toLowerCase();
}
as class variables are accessible inside class methods and you don't need to pass the class variables as arguments to same class methods
Same class variables are accessed this way only. Very simple example could be POJO classes, where you declare class variables and expose them through getter/setter methods. You don;t need to pass the class variables to these methods and some time, you can't(e.g. in getter methods).
Adding some thoughts around class variable vs. local variable in the method.
If there is a need of a variable which is theoretically associated with the class definition then the variable should be defined as class variable. e.g. employeeId, employeeName.. variables in a employee class should be defined as Employee class variables.
If there are variable needs which are local to a class method only and not required anywhere outside the method/class, then it should be defined as local variable inside the method.
If you are defining some utility methods to respond using some variables then those variables should be passed as argument to the util methods.
Back to your question:
If you are defining a entire class e.g. Sanitising, which has several methods around the string variable e.g. String class itself, then better to define your string as class variable and write the methods using the class variables.
But if you are defining Sanitising as a util/helper class then better to pass the string as method argument as normally you don;t want your util methods to be statefull (associated with the class instance).
To demonstrate good OO, you should definitly use
private String removeCaps(String y) {
return y.toLowerCase();
}
You can pass your Object, in this case your String in the global field x to the method as parameter. The String is then in the local field y and return the modified version.
I've read many large projects in OOP, and I notice that a lot of them use this.[variable], [ClassName].[staticVariable]. For example:
public class ABC {
private float mX;
public static float y;
public float getX() {
return this.mX;
}
public float doSomethingWithY() {
return ABC.y;
}
}
And even with Eclipse auto-generated Getters & Setters feature, it also comes with this.[variable], although it's unnecessary, because no local variable is declared there.
Is there any advantage when using these notations, or it's just a code style?
EDIT so some people don't misunderstand. I know what this and [ClassName].[staticVariable] stand for. But in this case, it's unnecessary. The question is: Even if it's unnecessary, why do guru coders still add it? When they need to update/fix a huge project, will there be any advantage and disadvantage?
Basically with this, you KNOW for sure that you are working with a class attribute, not with a variable created inside the method or maybe received as a parameter.
And also, it helps in case you have a local var with the same name.
And the final reason: readability.
It's necessary in some circumstances, for example this. is required when you need to use a member variable rather than a local method parameter of the same name.
It's also necessary for static variables where you need to be specific which class you want to get the static variable from (many classes could define static variables with the same name).
Apart from the necessary cases, it's really a matter of coding style. My recommendation is to use it whenever it helps to resolve potential ambiguity.
In complicated methods, it's sometimes nice to make a distinction between instance variables in this class, and local variables in a particular function. This distinction is immediately obvious when you use "this."
For small pieces of code it doesn't matter but sometimes this can happen:
public float getX() {
....
int mX = someFunc()
...
return mX;
}
In this case, the local value is returned instead of the member variable.
You normally want to be explicit and say this.mX. However, you shouldn't have huge functions anyway.
this.? '?' is a member variable, this is a reference to the current object.
see this
Its syntax,if you want to access instance variable of a class use the (reference of the object).(instance variable name) .Like
A a= new A();// for non static class,this for the current object
a.(instance variable name)
// for non static class do the same but use (class name).variable name