reserved word «this»
I would like an explanation with an example if possible, about the reserved word this in Java, I ended up not understanding very well.
this refers to the current object. Always read as soon as it will be clearer for you: this object Example:
public class Esse < public static void main(String[] args) < Esse esse1 = new Esse(); Esse esse2 = new Esse(); esse1.compara(esse2); >public void compara(Object aquele) < if(this == aquele) < System.out.println("mesmo objeto"); >else < System.out.println("Objetos diferentes"); >> >
Inside the main(), when calling the method compare() is implicitly passed the object that called it, in this case the object esse1 , then the comparison within the method returned false, for esse1 != esse2 It is also often said that this is the great difference of methods and functions, because when it is called a method its object is passed implicitly with it, and the same does not occur with functions in other languages, for example Pascal. I said «I used to say» because it is what some people defend (including I), but despite everything in Java being method and never functions, there are static methods that do not have an object attached to it, because static methods belong to the class and not to the object, so it is not necessary that there is an object created so that they are accessed. Example:
The above code is invalid because the method does not belong to the object, but to the class, then the object this is not passed to the method that was called. O this It is also very commonly used to explain which variable we are talking about, whether it is the variable of the object or whether it is a local variable. Example:
public class Exemplo < private int id; public int getId() < return id; >public void setId(int id) < this.id = id; >>
Watch the line this.id = id , it is assigning the value of the local variable to the value of the variable of the object that was called the set method. If it was not possible to resort to this variables should have distinct names for the code to work properly.
The this Reserved Word in Java
This is part 5 of my series, Java Object Oriented Programming Core. A reserved word in a computer language is a word that you cannot use arbitrarily. It has a special meaning in the language. Java is case sensitive, so all its reserve words are case sensitive. In this part of the series I explain to you the meaning of the Java reserved word, this.
Meaning of the this Reserved Word
The reserved word, this, is a reference to the instantiated object whose member method is being executed. So, inside a method, you can use the «this» reserved word as the instantiated object variable to access a property of the same object or to access another method of the same object. The following code gives an illustration for accessing a property:
void assignShow()
this.num1 = 12;
System.out.println(num1);
>
>
class ThisReserved
public static void main(String[] args)
MyClass myObj = new MyClass();
myObj.assignShow();
>
>
In Java, the variable of an instantiated object is a reference: meaning it refers to the object and does not replace the object. The reserved word, this, is predefined in Java. It is a reference to the object whose method is being executed. It has to be coded in the class method of interest. Any method has its time of execution in an object.
The referenced object here is the object instantiated from a class, whose method is in the process of execution. As the method is being executed, using the word, this, would refer to the method�s object. That is how the Java class was designed to work.
In the above code, the method assignShow() uses the reserved word, this, which is the reference to its object (the object is instantiated from the class). Line 1 in the method uses �this� to access the property, num1. It was not very necessary just to assign a value to a property this way, as we could have used num1 directly, because a method can access a property of the same class (object). However, it was done to illustrate the use of the �this� reserved word. Note the use of the dot operator with the �this� reserved word. The dot operator is the operator to use to join a class object reference and the object property (or method) in code. Read and try the above code.
The following example illustrates the use of the �this� reserved word for a method (called aMethod). Read and try it:
void aMethod()
System.out.println(«I am alive!»);
>
class ThisReserved2
public static void main(String[] args)
MyClass myObj = new MyClass();
myObj.assignShow();
>
>
So, �this� is used to access the properties and methods in a method of the object under execution. «this» goes into action when the method in which it is coded is operating.
Why not use an instantiated object variable, in place of, this? Answer: Normally you code �this� in a class declaration (description). Many objects have to be instantiated from that same class. You may not know the variable name of a future instantiated object while coding the class. So �this� would represent any future variable (name).
Well, let us end here and continue in the next part of the series.
Reserved words as names or identifiers
Is there any tricky way to use Java reserved words as variable, method, class, interface, package, or enum constant names?
It’s not so strange, that he want do that. That’s why C# has @ prefix, and Delphi has & and variable or method named eg. @if is legal in C#.
I don’t get all the «don’t do it» comments. It is perfectly legitimate to call APIs from Java that weren’t themselves written in Java, and there are identifiers which are perfectly legal in JVM byte code which aren’t legal in Java. That’s precisely why languages like C# ( @class ), Scala ( `class` ) and others have escaping mechanisms. There are 500 languages on the JVM, if I tried to take every single reserved word from every single one of those 500 languages into account when designing APIs, I’d go insane (and someone might invent a new language with a new reserved word later anyway).
13 Answers 13
This is a valid question. Such a thing is possible in other languages. In C#, prefix the identifier with @ (as asked before); in Delphi, prefix with & . But Java offers no such feature (partly because it doesn’t really need to interact with identifiers defined by other languages the way the .Net world does).
Well, if you are willing to accept the C# hack, you can prefix Java names with ZZZ or any other character sequence that you won’t otherwise use as a prefix.
But Ira, that changes the identifier. The C# and Delphi ways escape the original name, but it’s still the same name. In Delphi, you can even write the fully qualified name without the escape character.
This becomes especially visible in Xml or JSON serialization as the serialized text would have ZZZ as part of the tag name , whereas in C#, @string would serialize to .
It came up for me with protocol buffer definitions that used a Java keyword. Code generation is really useful, but it’s harder to make it work in a language-agnostic way if target languages forbid you to be agnostic about them.
No, there is no way. That’s why they’re labeled «reserved».
Most often this issue comes up for «class», in this case it is customary to write «clazz».
Strictly speaking you can’t, unless you get your hands on a buggy compiler implementation that doesn’t adhere to the Java language spec.
But where there’s a will, there’s a way. Copy the following code into your IDE, switch the source file encoding to UTF-16 and here we go:
public class HelloWorld < public static void main(String[] args) < HelloWorld.nеw(); >public static void nеw () < System.out.println("Hello,World"); >>
This code is a well-formed and valid Java class. However, as you have guessed there is a little trick: the ‘е’ character within «new» identifier does not belong to the ASCII character set, it is actually a cyrrilic ‘е’ (prounanced ‘YE’).
Current Java language spec explicitly permits, and this an important point to make, the use of Unicode for naming identifiers. That means that one has an ability to freely call her or his classes in French, Chinise or Russian if they wish. It is also possible to mix and match the alphabets within code. And historically, some letters within Latin and other alphabets are lookalikes.
As a result: no, you can’t use the reserved words as identifiers, but you can use identifiers that look exactly like reserved words.
Whether anyone should be doing it is a totally different matter.
java – Reserved word «this»
I would like an explanation with an example if possible, about the reserved word this in Java, I just didn’t understand very well.
Answer:
this refers to the current object. Always read so it becomes clearer to you: this object
public class Esse < public static void main(String[] args) < Esse esse1 = new Esse(); Esse esse2 = new Esse(); esse1.compara(esse2); >public void compara(Object aquele) < if(this == aquele) < System.out.println("mesmo objeto"); >else < System.out.println("Objetos diferentes"); >> >
Inside main(), when calling the compare() method, the object that called it is implicitly passed, in this case the esse1 object, so the comparison inside the method returned false, because esse1 != esse2
In fact, it is usually said that this is the big difference between methods and functions, because when a method is called its object is implicitly passed along with it, and the same does not happen with functions in other languages, for example Pascal.
I said «they say» because that’s what some people advocate (myself included), but even though everything in Java is a method and never functions, there are static methods that don’t have an object attached to them, because static methods belong to class and not the object, so it is not necessary that there is an object created for them to be accessed.
The code above is invalid because the method does not belong to the object, but to the class, so the this object is not passed to the method that was called.
The this is also very commonly used to spell out which variable we are talking about, it is the variable of the object or whether it is a local variable. Example:
public class Exemplo < private int id; public int getId() < return id; >public void setId(int id) < this.id = id; >>
Notice the line this.id = id , it is assigning the value of the local variable to the variable value of the object that the set method was called. If it was not possible to resort to this the variables would have to have different names for the code to work correctly.