This usage in java

This usage in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Using the this Keyword

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 .

Читайте также:  Php дата как в базе

Using this with a Field

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

For example, the Point class was written like this

but it could have been written like this:

Each argument to the constructor shadows one of the object’s fields — inside the constructor x is a local copy of the constructor’s first argument. To refer to the Point field x , the constructor must use this.x .

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here’s another Rectangle class, with a different implementation from the one in the Objects section.

public class Rectangle < private int x, y; private int width, height; public Rectangle() < this(0, 0, 1, 1); > public Rectangle(int width, int height) < this(0, 0, width, height); > public Rectangle(int x, int y, int width, int height) < this.x = x; this.y = y; this.width = width; this.height = height; >. >

This class contains a set of constructors. Each constructor initializes some or all of the rectangle’s member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor creates a 1×1 Rectangle at coordinates 0,0. The two-argument constructor calls the four-argument constructor, passing in the width and height but always using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number and the type of arguments.

If present, the invocation of another constructor must be the first line in the constructor.

Источник

Ключевое слово this

Java-университет

Ключевое слово this <в примерах data-lazy-src=

Таким образом, здесь this позволяет не вводить новые переменные для обозначения одного и того же, что позволяет сделать код менее «перегруженным» дополнительными переменными.

Пример второй — Применение this для явного вызова конструктора

Вызов одного конструктора из другого может пригодиться тогда, когда у вас (как ни странно) несколько конструкторов и вам не хочется в новом конструкторе переписывать код инициализации, приведенный в конструкторе ранее. Запутал? Все не так страшно как кажется. Посмотрите на код ниже, в нем два конструктора класса Human :

 class Human < int age; int weight; int height; Human(int age, int weight)< this.age = age; this.weight = weight; >Human(int age, int weight, int height) < //вы вызываете конструктор с двумя параметрами this(age, weight); //и добавляете недостающую переменную this.height = height; >> 

Здесь у нас сначала приводится конструктор с двумя параметрами, который принимает int age и int weight . Допустим, мы написали в нем две строчки кода:

 this.age = age; this.weight = weight; 

а потом решили добавить еще один конструктор, с тремя параметрами, который помимо возраста и веса принимает еще и рост. В новом конструкторе вы бы могли написать так:

 this.age = age; this.weight = weight; this.height = height; 

Но вместо того, чтобы повторять уже написанный ранее код в этом конструкторе, вы можете с помощью ключевого слова this явно вызвать конструктор с двумя параметрами:

 this(age, weight); // и дописываете недостающую переменную: this.height = height; 
  • вызови this (этот) конструктор, который имеет два параметра.
  • и добавить недостающую переменную.

Ключевое слово this <в примерах data-lazy-src=

this Keyword in Java: What is & How to use with Example

this keyword in Java is a reference variable that refers to the current object of a method or a constructor. The main purpose of using this keyword in Java is to remove the confusion between class attributes and parameters that have same names.

Following are various uses of ‘this’ keyword in Java:

  • It can be used to refer instance variable of current class
  • It can be used to invoke or initiate current class constructor
  • It can be passed as an argument in the method call
  • It can be passed as argument in the constructor call
  • It can be used to return the current class instance

Click here if the video is not accessible

Understand ‘this’ keyword with an example.

this Keyword in Java

  1. Class: class Account
  2. Instance Variable: a and b
  3. Method Set data: To set the value for a and b.
  4. Method Show data: To display the values for a and b.
  5. Main method: where we create an object for Account class and call methods set data and show data.

Let’s compile and run the code

Our expected output for A and B should be initialized to the values 2 and 3 respectively.

But the value is 0, Why? Let investigate.

this Keyword in Java

In the method Set data, the arguments are declared as a and b, while the instance variables are also named as a and b.

this Keyword in Java

During execution, the compiler is confused. Whether “a” on the left side of the assigned operator is the instance variable or the local variable. Hence, it does not set the value of ‘a’ when the method set data is called.

this Keyword in Java

The solution is the “this” keyword

Append both ‘a’ and ‘b’ with the Java this keyword followed by a dot (.) operator.

this Keyword in Java

During code execution when an object calls the method ‘setdata’. The keyword ‘this’ is replaced by the object handler “obj.” (See the image below).

this Keyword in Java

So now the compiler knows,

  • The ‘a’ on the left-hand side is an Instance variable.
  • Whereas the ‘a’ on right-hand side is a local variable

The variables are initialized correctly, and the expected output is shown.

this Keyword in Java

Suppose you are smart enough to choose different names for your instance variable and methods arguments.

this Keyword in Java

But this time around, you create two objects of the class, each calling the set data method.

How the compiler will determine whether it is supposed to work on instance variable of object 1 or object 2.

this Keyword in Java

Well, the compiler implicitly appends the instance variable with “this” keyword (image below).

this Keyword in Java

Such that when object 1 is calling the set data method, an instance variable is appended by its reference variable.

this Keyword in Java

While object 2 is calling the set data method, an instance variable of object 2 is modified.

this Keyword in Java

This process is taken care by the compiler itself. You don’t have to append ‘this’ keyword explicitly unless there is an exceptional situation as in our example.

Example: To learn the use “this” keyword

Step 1) Copy the following code into a notepad.

Источник

Оцените статью