Computer Science
Java This Keyword
In Java, "this" is a keyword that refers to the current object. It is used to differentiate between instance variables and local variables with the same name, and to call one constructor from another constructor in the same class. The "this" keyword can also be used to pass the current object as a parameter to other methods.
Written by Perlego with AI-assistance
Related key terms
1 of 5
6 Key excerpts on "Java This Keyword"
- eBook - ePub
IT Interview Guide for Freshers
Crack your IT interview with confidence
- Sameer S Paradkar(Author)
- 2019(Publication Date)
- BPB Publications(Publisher)
main() method and will be executed only once.Keywords and operators
What is "this" reference in Java?
To refer to the current object, this keyword is used. When we want to pass the instance of the current object to a method in another object, we pass the current instance as follows:otherobj1.anymethod(this);If a variable of an object and the parameter name of a method in the object are the same, we use this keyword to avoid ambiguity as follows:String name; public void method1(String name){ this.name=name; }The this keyword included in parenthesis, that is, this() with or without parameters is used to call another constructor. The default constructor for the Car class can be redefined as follows:public Car(){ this(“NoBrand”,””NoColor”,4,0); }The this() keyword can be invoked only from a constructor and should be the first statement in the constructor.State the significance of public, private, protected, default modifiers both singly and in combination.
Access specifiers are the attributes that determine whether a class member is accessible or not. Different types of access modifiers are as follows:- The public class is visible in other packages; the field is visible everywhere (the class must be public too)
- The private methods or variables canbe used only by an instance of the same class that declares them. A private member can only be accessed by the class that declares the member.
- The protected
- eBook - PDF
- Todd Greanier(Author)
- 2006(Publication Date)
- Sybex(Publisher)
The syntax for referencing a method named parentMethod from a child class would simply be super.parentMethod(); You can go up only one level to your direct super class. If your parent class also extends another class, there is no way to directly access the “grandparent” class. A call such as super.super.method() is not allowed. The this Keyword Much like super , the this keyword is a standard name for a reference that you will need from time to time. In this case, the reference is not to any parent class, but to yourself. In other words, when you use this , you are referring to this instance . You use the this keyword inside your method bodies in two different cases. First, you can use it to clarify that the variables and methods being called belong Keywords and Operators 73 to one particular instance. Second, you can pass it as a parameter to or a return type from a method. As a quick example of how this works, here is a modified version of the Robot class. Notice that the name variable is now private and that there are two new methods, one for setting the value of name and one for getting the value of name . 1 public class Robot2 2 { 3 private String name; 4 5 public void setName(String name) 6 { 7 this.name = name; // cannot say name = name; 8 } 9 10 public String getName() 11 { 12 return name; 13 } 14 } The Robot2 class works quite a bit differently from the original Robot class, but the results are the same. Make a note of how this class looks because this is well constructed. In the previous example, the name variable was declared as public , which is perfectly legal but not good practice. Generally, all the vari-ables defined in the class should be private so that no external users can modify their value directly. Instead, you should provide one or more public methods that handle access and modification of the variable. - eBook - PDF
Elementary Synchronous Programming
in C++ and Java via algorithms
- Ali S. Janfada(Author)
- 2019(Publication Date)
- De Gruyter Oldenbourg(Publisher)
Furthermore, two static methods getCount() and callCount() are created which access to these static 82 | Fundamental concepts of programming in Java data members. Moreover, the static method callCount() is called in the static method getCount() . As shown in the left program, both static data members are defined after ending the class. However, as previously mentioned, this is unnecessary in Java un-less we want to initialize a value to the data member. In the right program, we initial-ized the static data member to 10 within a static block. As demonstrated in both pro-grams, the static methods are directly called without creating any object. 3.3.6 The this keyword The this keyword is commonly used in both C++ and Java languages. There are vari-ous applications of this keyword in both languages. However, due to the calculation aim of the present book, we do not need all the applications in our programs and only one feature is used in several programs. Moreover, the this keyword in C++ is an important pointer accessible only within the non-static member functions of a class and points to the object for which the mem-ber function is called. However, in Java, the this keyword is an instance variable which refers to the current object in a method or constructor. As explained above, using the thi s keyword is nearly the same in both lan-guages. The most common use of the this keyword in both C++ and Java is to resolve the ambiguity between the instance variables and parameters with the same name. This can be accomplished by the following syntaxes: C++ codes: J ava codes: this-> va r = va r ; this. va r = va r ; where, the variable var is simultaneously regarded as an instance variable and a pa-rameter. In the left C++ codes, this-> var means (this*). var , in the literature of the pointers (Section 2.3). To clarify the above discussions, consider Programs P3-14. - No longer available |Learn more
Introduction to Programming
Learn to program in Java with data structures, algorithms, and logic
- Nick Samoylov(Author)
- 2018(Publication Date)
- Packt Publishing(Publisher)
This class seems to not have a constructor. So, how are the states of the objects based on this class going to be initialized? The answer is that, in fact, each class that does not define its constructor explicitly but gets a default one—without parameters. And here are two examples of constructors added explicitly—one without parameters, another with a parameter:public class SomeClass { private int field1; public MyClass(){ this.field1 = 42; } //... other content of the class - methods // that define object behavior}public class MyClass { private int field1; private String field2; public MyClass(int val1, String val2){ this.field1 = val1; this.field2 = val2; } //... methods here}In the preceding code snippet, the keyword this indicates the current object. Its usage is optional. We could write field1 = val1; and achieve the same result. But it is a good practice to use the keyword this to avoid confusion, especially when (and programmers often do this) the name of the parameter is the same as the name of the field, such as in the following constructor:public MyClass(int field1, String field1){ field1 = field1; field2 = field2;}Adding the keyword this makes the code more friendly to human eyes. And sometimes, this is needed. We will discuss such cases in Chapter 6 , Interfaces, Classes, and Objects Construction .A constructor can also call the methods of this or any other accessible class:public class MyClass { private int field1; private String field2; public MyClass(int val1, String val2){ this.field1 = val1; this.field2 = val2; method1(33); method2(val2); } public String method1(int i){ //statements, including return statement } private void method2(String s){ //statements without return statement }}If a class does not define a constructor explicitly, it gets a default constructor from the default base class java.lang.Object. We will explain what it means in the upcoming Inheritance section .A class can have several constructors with different signatures that can be used to create objects with different states if an application logic requires it. Once an explicit constructor with parameters is added to a class, the default constructor is not accessible unless it is added explicitly too. To clarify, this class has only one—default—constructor: - eBook - ePub
- Nick Samoylov(Author)
- 2022(Publication Date)
- Packt Publishing(Publisher)
The five reserved identifiers in Java are as follows:- permits
- record
- sealed
- var
- yield
Reserved words for literal values
The three reserved words in Java are as follows:- true
- false
- null
Restricted keywords
The 10 restricted keywords in Java are as follows:- open
- module
- requires
- transitive
- exports
- opens
- to
- uses
- provides
- with
They are called restricted because they cannot be identifiers in the context of a module declaration, which we will not discuss in this book. In all other places, it is possible to use them as identifiers, such as the following:String to = "To"; String with = "abc"; Although you can, it is a good practice not to use them as identifiers, even outside module declaration.Usage of the this and super keywords
The this keyword provides a reference to the current object. The super keyword refers to the parent class object. These keywords allow us to refer to a variable or method that has the same name in the current context and the parent object.Usage of the this keyword
Here is the most popular example: class A { private int count; public void setCount(int count) { count = count; // 1 } public int getCount(){ return count; // 2 } }The first line looks ambiguous, but, in fact, it is not – the local variable, int count , hides the int count private property instance. We can demonstrate this by running the following code:A a = new A(); a.setCount(2); System.out.println(a.getCount()); //prints: 0Using the this keyword fixes the problem:class A { private int count; public void setCount(int count) { this.count = count; // 1 } public int getCount(){ return this.count; // 2 } }Adding this to line 1 allows the value to be assigned the instance property. Adding this to line 2 does not make a difference, but it is good practice to use the this keyword every time with the instance - Jocelyn O. Padallan(Author)
- 2020(Publication Date)
- Arcler Press(Publisher)
A class can consists of any of the following types of variable. • Local variables: The local variables are the variables that are defined inside methods, constructors or blocks. The local variables are usually declared and initialized within the method and the variable will be destroyed when the method has completely executed. • Instance variables: The kind of variables that exist within a class but are present outside any method are known as the Instance variables. This type of variables is initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. • Class variables: The variables that are declared within a class, outside any method, along with the static keyword are known as Class variables. 3.5.2. Objects in Java Programming It is the fundamental unit of the Object-oriented Programming. The real-life Introduction to Computer Programming and Numerical Methods 82 entities are denoted by the objects. A typical Java program creates many objects which interact with the help of invoking methods. An object contains: State: Attributes of an object represent the state. The state depicts the properties of an object. Behavior: The behavior explains the methods of an object. Also, it depicts the response of an object with other objects. Identity: Identity makes the object unique while enabling one object to interact with the other objects. Example of an object: dog Table 3.1. Difference between Class and Objects in Java Object Class Object is defined as an instance of a class. Class is defined as a blueprint or tem -plate from which objects are created. Object is considered as a real-world entity like laptop, bed, mouse, chair, pen, mobile, keyboard, etc. Class is defined as a group of similar objects. Object is a physical entity.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.





