This question already has answers here:
In Java, why do people prepend fields with `this`?
(16 answers)
Closed 8 years ago.
I am looking at a very old code-base, and every field access follows this pattern:
void method() {
TYPE fieldRef = this.field;
// Use fieldRef instead of field
}
I can't figure out why this pattern is followed rigorously. Is there some performance benefit to this? Does it have something to do with how fields behave with inheritance?
this always refers the current class variables in the scenario you mentioned
so the benefit is just that the purpose of assigning value is satisfied the way it should be
Is there some performance benefit to this?
No its not for performance improvement
Does it have something to do with how fields behave with inheritance?
only if your parent class variables have same names Yes, or it does not have any thing to do with Inheritance as well
EDIT:
// Use fieldRef instead of field
this we usually do because in java if your field is an Object, it maintains reference and any modifications we do gets reflected in original object property.
Maybe the coder wants to catch the instance object that this.field refers to with a temporary reference and immediately assign a different instance object to this.field.
Related
This question already has answers here:
Why make defensive copies in getters inside immutable classes?
(7 answers)
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 3 years ago.
I'm learning Java and I have some doubts.
If defined a class with a private variable like
class test<A>{
private A var;
...
public A get(){
return var;
}
}
Is the get method wrong?
I think so because with this definition I can modify the variable "var" like
test<A> x = new test<A>();
A temp = x.get();
temp.set(*something*);
At the end x is changed (I tested it using Vector as A). If I understand correctly, this works because object reference (I miss C pointers, sob). Am I wrong? Maybe I don't understand the purpose of the keyword "private"! Thanks in advance!
Edit: I have no problems with "pass-by-reference" and "pass-by-value". I have doubts defining get() method for a private variable in a class (you don't say?). Please stop linking Is Java "pass-by-reference" or "pass-by-value"?
If your getter method is returning a reference to a mutable object, then this greatly weakens the quality of the encapsulation provided by your class, because it becomes possible to modify the state of an instance of your class without calling a method of the class.
One standard strategy to guard against this problem is what J. Bloch calls defensive copies (Effective Java, 3rd edition, Item 50: "Make defensive copies when needed").
This would mean creating a copy of var in the getter method, and returning that copy instead. How to do this depends on the design of A.
Because A is a type parameter, making a copy of the instance requires additional support in the design. To see how to achieve this using Java's cloning mechanism, see my answer to the post "Does it make sense to create a Copyable type interface instead of using Cloneable?".
If this is a problem, you can create a façade to protect your variable
public class Facade extends A {
A myObj;
public Facade (A obj) {
myObj =
}
public A get(){
return myObj.get();
}
public B set(Object val) {
throw new RuntimeException("Setting is not allowed");
}
}
This might be a bit too much detail for just starting, but you might review class java.util.concurrent.atomic.AtomicReference<V>, which is very similar to your example.
Generally speaking, placing instance variables in private variables, while providing access to the variable using a getter and a setter, is standard practice.
Note that your class name should be capitalized, type parameter 'V' is more standard, and the variable name would more usually be 'value'. Also, try to pick a more communicative name for the class. (Type parameter type variable could be 'ValueType', which would fit some preferences. But, single character type variable names are more usual.)
public class Wrapper<V> {
private V value;
public V get() {
return value;
}
public void set(V value) {
this.value = value;
}
}
I'd add some other point here: as others have said, you hand out the object reference and it can be modified, which could be bad.
Object orientation is about keeping the data and the code that works on it in one place. If you need getters, think what the callers of the getters need to do, and whether that action should rather be a method on the class that has the data. Your code could suffer from the Feature Envy code smell, as it violates the Tell, Don't Ask principle.
To fix this, remove the getter, and introduce new methods as needed. For example, if you have some data object that needs to get printed, you could pass the Printer to the object and have it print itself to the given Printer.
If you're dealing with a collection class (just a guess from your template parameter), you may need to keep the getter, but then you're probably not concerned with the caller changing the value anyway.
This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 5 years ago.
For instance, lets say that we have an object called car which is a part of Cars class and it has a color property. And assuming that we have a getter for the color such that:
public String getColor(){
return color;
}
But should not it be this.color? If not, why?
You use this implicitly here. When you "leave" out the object on which you "access" a field or call a method ... then that is the same as saying this.field or this.foo() Unless of course, that the name you are using refers to a local variable for example. So, just to be precise: when you have code such as
void setter(Whatever foo) {
this.foo = foo;
then of course you have to use this in order to differentiate between the field foo and the local variable foo that is shadowing that field.
Any slightly experienced Java programmer knows that. Therefore it is good practice to not write down this here. Keep in mind: you write your code so that your human readers understand what is going on. The compiler and IDEs are fine with using this ... or not using this. But for your human readers it simply means a little bit less of information to process when you leave out this keyword here.
That is all there is to this.
'this' always represents current object. SO if you say this.color it's excatly same as simply say 'color'. You can doesn't mean you should :)
It's superfluous. In general you use the this.something only if you have a parameter in the method's signature with the same name. Classical example are constructors:
public MyClass(String val1, String val2) {
this.val1 = val1;
this.val2 = val2;
}
It was used more often in the past when there was no syntax highlighting in IDEs that included the different presentation of member and local variables. Then this was used to make it easier to distinguish between these two types of variables.
This question already has answers here:
Why is assignment to 'this' not allowed in java?
(7 answers)
Closed 8 years ago.
It seems a thing that almost no one has realized, but the "this reference" in Java is final. In a normal programming day I thought I could redefine the entire instance by redefining the this reference inside the own class:
public void method() {
this = new MyObject("arg1", arg2, arg3); //it throws a compile error
}
Why the this reference is final in Java?
The problem is not that this is a final reference - it's not itself a reference at all. this is a keyword that "denotes a value that is a reference to the object for which the instance method or default method was invoked" (JLS §15.8.3).
Furthermore, it wouldn't make sense to reassign it in the sense that a variable can be reassigned. Remember that reassigning a reference changes only that reference, and not other references that might point to the same object. So reassigning this would not only be insane but also useless.
I find this question interesting from a theoretical point of view.
From a technical point of view this cannot work, as in Java we have pass-refererence-by-value ( http://www.javaworld.com/article/2077424/learn-java/does-java-pass-by-reference-or-pass-by-value.html ) and cannot swap out objects where some other parts of code hold a reference to that object -- i.e. a true swap method is not possible in Java (see the linked article).
While you could theoretically reassign this, all other references to the object would not change and make the operation pretty senseless.
The closest thing you can achieve is a copy constructor.
this is not a variable you can assign a value to. It is a built-in expression returning the object that is the context for the method currently executing.
While re-assigning this might be useful for some nice hacks, it would mess up all kind of things.
The this keyword is used to provide a reference to the current object within its class. Mostly, it is used to clarify scope issues with local variables which have the same identifier as a class member. E.g.
public void function (int param) {
this.param = param
}
Reassigning it to another object goes beyond the task assigned to the keyboard. What you want to do, (reassing a reference) can be achieved on the upper context, i.e. the context in which the object was created (and a reference to it was assigned).
Wrong thinking about this. this is just a keyword(not variable) in java which referenced to current instance and its a compilation restriction that keyword(any not only this) can not be initialized.
This question already has answers here:
What is the memory overhead of a Java method?
(7 answers)
Closed 8 years ago.
Also, does the size of the method affect how much more space each object would take up (if the answer to the title question is yes)? Or would it be more like a reference to the method, each reference being the same size? Thanks.
Methods don't add memory space to instance variables, only to the class itself (which is of course also an Object :-)).
Methods and static members of the class are simply represented once in the VM as part of the class definition. The size of each individual instance should only be affected by the non-static member variables in the class.
As far as I know, a method does not influence the size of the object. It will increase the file size, but not the object size.
Each object has a reference to its class. The number of methods in that class don't matter.
The number of non-static fields make a difference to each object as every object need to have that field. (Unless the JVM optmises away the field)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why would one mark local variables and method parameters as “final” in Java?
I was checking some Java code, I am not good at java at least have some knowledge what final does such as sealed classes, readonly fields and non-overridable methods but this looks weird to me, declaring a variable final in methods:
private static void queryGoogleBooks(JsonFactory jsonFactory, String query) throws Exception {
// Set up Books client.
final Books books = Books.builder(new NetHttpTransport(), jsonFactory)
.setApplicationName("Google-BooksSample/1.0")
.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) {
BooksRequest booksRequest = (BooksRequest) request;
booksRequest.setKey(ClientCredentials.KEY);
}
})
.build();
Could you tell me what the meaning of final is in this context?
Here is the complete code:
http://code.google.com/p/google-api-java-client/source/browse/books-cmdline-sample/src/main/java/com/google/api/services/samples/books/cmdline/BooksSample.java?repo=samples
It simply makes the local variable books immutable. That means it will always be a reference to that same Book object being created and built, and cannot be changed to refer to another object, or null.
The Book object itself is still mutable as can be seen from the sequence of accessor calls. Only the reference to it is not.
In this case, final Books books simply means that books must be assigned a value exactly once.
I like to use the final keyword like this as it shows intent of the variable, which I find to be valuable information when looking at code as it removes yet another variable from the situation...so to speak.
If I don't mark a variable as final then it stands out as something to keep my eye on because it's going to change values sometime soon. This information is helpful while, for example, stepping through the code in the debugger or refactoring & moving around code.
For further reading on all things final: The Final Word On the final Keyword
This likewise makes the variable reference read-only. Usually, this is to protect the code from accidentally modifying a variable that must not change.
I'm pretty sure it means nothing more than the variable books cannot be overwritten later on in the method.
This code is using anonymous class JsonHttpRequestInitializer, where it refers to the local variable in method queryGoogleBooks, the problem in this kind of situation is that the queryGoogleBooks method could return before initialize method of the JsonHttpRequestInitializer is completed, where it could cleanup the variable and could cause the initialize method of JsonHttpRequestInitializer to fail. So it is required to declare the variables as final in this type of situations. For more details refer to,
Cannot refer to a non-final variable inside an inner class defined in a different method