Why is the "this" keyword final in Java? [duplicate] - java

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.

Related

why getClass() from superclass variable returns subclass class name? [duplicate]

This question already has answers here:
Dynamic dispatch and binding
(2 answers)
Closed 2 years ago.
Im confused, when i use getClass( ) from a superclass reference variable that's pointing to a subclass object, the result is the subclass.
Heres a simple example:
public `class` TestGetClass
{
public static void main(String[] args)
{
Object obj = new Integer(20);
System.out.println("obj class: " + obj.getClass());
}
}
The output gives me the Integer class instead of the Object class.
obj class: class java.lang.Integer
Can someone explain please
What you're looking for is simply:
Object.class.
obj.getClass() in java could plausibly be interpreted in two different ways:
It means: Take the expression 'obj', which is a reference (i.e., a pointer). Follow the pointer and find the object it is pointing at. Ask that object what its type is.
just like 1, except, because the variable type was Object, invoke the implementation of the getClass() method from the java.lang.Object class. i.e., no dynamic dispatch.
It means: Take the locally declared variable named obj. What type did I declare it as, right here in this method? Don't care about the object/pointer at all, just the declaration.
Now, the java lang spec is crystal clear: In java, #1 is what happens. #2 is not available (you can't opt out of dynamic dispatch. As a matter of obvious language design, private methods don't do it because they don't need it, and static methods don't do it because, by being static, they just aren't a part of the hierarchy in the first place - so those seeming exceptions really don't apply. There is no other way to opt out).
Here's the thing about option #2 though: is completely pointless.
In java, you can't have mystery meat variables. Somebody declares them, and the type is written right there in the source file. There is no such thing as 'eh, figure it all out at runtime'. Even java10's var doesn't work that way (it's still locked in, for sure, at compile time).
So, you already know. It is object, what point is there to repeat it?
If you want a java.lang.Class<?> instance that represents Object, there's syntax for this. it is:
Class<?> objClass = Object.class;

Is there a benefit for accessing fields via `this`? [duplicate]

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.

How does the special variable "this" know exactly which Object to refer to in a program in JAVA? [duplicate]

This question already has answers here:
Using the keyword "this" in java [duplicate]
(12 answers)
Closed 9 years ago.
If the special variable this refers to an Object in a variable/method that is being used. How does it know exactly which object it must refer to out of various objects in a program?
The mechanism is almost disappointingly simple.
Each instance method actually takes one more argument than you declare for it, and that extra argument is assigned to this. Java syntax just thinly disguises this. When you write
list.get(0);
you have actually written
get(list, 0);
in a slightly modified way. The Java runtime resolves which get method to call by inspecting the type of that first argument and locating the appropriate get method in its class.
this points to the current object instance that it is used in.
If you define a class A with a method() that contains a this reference then you create two instances of the class
A a1 = new A();
A a2 = new A();
If you call a1.method() then this will refer to a1, if you call a2.method() then this will refer to a2
A a = new A();
a.doSomething(i) // is same as calling doSomething(a, i).
So, internally this refers to "a". The first argument to the function will be the object (there will only be one method that will be used by all objects). So, argument o will be the current object which has called this function.
From JAVA LANGUAGE SPECIFICATION
The keyword this may be used only in the body of an instance method,
instance initializer, or constructor, or in the initializer of an
instance variable of a class. If it appears anywhere else, a
compile-time error occurs.
When used as a primary expression, the keyword this denotes a value
that is a reference to the object for which the instance method was
invoked (§15.12), or to the object being constructed.
The type of this is the class C within which the keyword this occurs.
At run time, the class of the actual object referred to may be the
class C or any subclass of C.
The keyword this is also used in a special explicit constructor
invocation statement, which can appear at the beginning of a
constructor body (§8.8.7).
You can also refer to Oracle Tutorials
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.
Oracle Java Tutorials
this is a very important keyword that can differentiate between parent and child class objects. this refers to the present context in which object has too be referred to..!!

Pass by value or reference . Simple View [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is Java pass by reference?
After reading the discussion on this topic, can one conclude that when Java passes a variable, say A (excluding primitive type), it means it passes the object, which the variable (A) is referencing. So any changes made on that object reflects in variable (A). So at last does it work as pass by reference in general term?
No, that's not correct.
Everything is passed by value in JAVA - no exceptions!
However it's crucial to understand that what you pass is not the object, but a reference to it.
This reference is passed by value (so you can't change it in the method).
You indeed can alter the objects data through this reference, but as I said - you can't change the reference to refer to a different object (or null for that matter).
Java passes parameters to methods using pass by value semantics. That is, a copy of the value of each of the specified arguments to the method call is passed to the method as its parameters.
Note very clearly that a lot of people confuse the "reference" terminology with respect to Java's references to objects and pass by reference calling semantics. The fact is, in dealing with Java's references to objects, a copy of the reference's value is what is passed to the method -- it's passed by value. This is, for example, why you cannot mutate the (original, caller's) reference to the object from inside the called method.
"pass by reference" means if you pass a variable into a method, its value can be modified. This is possible in many languages, like Pascal, Ada, and C++, but not in many other languages like C and Java.
here is a good discussion about it . http://www.jguru.com/faq/view.jsp?EID=430996
See Is Java "pass-by-reference" or "pass-by-value"?
Java is always calls-by-value. In the case of when objects are passed it passes the "value of the reference" which gives Java the semantics of call-by-object-sharing (it does this through call-by-value-of-the-reference though!).
I like to say: When an object is passed it is not copied. Then, since it is the same object on the inside of the method -- the variable is just a different "name" for it -- if you change the object (not the variable!) inside the method, you change that object outside -- everywhere, really -- as well. (It is the same object, ater all :-)
Please note that variables are never passed. They are evaluated as expression and the values that they evaluate to are passed.
Some languages like C++ support call-by-reference. This is different than either call-by-value or call-by-object-sharing because these functions are called with (a generally restricted set of) "lvalues" as arguments and reassignment to the parameters in the function will affect the "lvalues" on the outside. "lvalues" are normally variables and support for this kind of calling convention differs by language (many do not support it!).
Happy coding.
Java does not pass by reference. It also does not pass objects. It passes object references by value. Inside a method, you can make changes to the object that was passed, but you cannot change the reference itself in the calling code.
void foo(Object obj) {
foo = new Object();
}
Object obj = new Object();
Object obj2 = obj;
foo(obj2);
System.out.println("obj2 passed by " + (obj == obj2 ? "value" : "reference"));
This code will print "pass by value".
I would conclude more along the lines of:
Java passes all parameters, primitive and non-primitive, by value. In the case of non-primitive types, what Java actually passes is a pointer (or "reference") to the object instance, by value. This means that the caller's copy of the reference itself (i.e. the memory location that the pointer actually points to) cannot be changed. But at the same time, any state internal to the referenced object instance that the callee modifies will be modified in the caller's "copy" of the object as well, because there is in fact only a single instance of the object that both the caller and callee share.

final variable in methods in Java [duplicate]

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

Categories