Use of this operator in java

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest.

This keyword is used in Java.

  • this keyword is used six times in Java.
  • this can refer to the variable in the existing class instantiation.
  • this may be used to execute the existing class function (implicitly)
  • this() can be called the function Object() of the current class.
  • this can be given as a result of a variety of arguments.
  • this function Object() call can be provided as a parameter.
  • this could be employed to return the product’s current class instance.

1) this: that refers to the existing class object instance

This keyword can be employed to refer to the existing class object instance. This phrase eliminates ambiguity among local variables and arguments.

Addressing the issue without all this keyword

Let’s look at an example of what occurs if we don’t utilize this search term:

Example: Students.java

class Students < int rollnos; String names; float fees; Students(int rollnos,String names,float fees)< rollnos=rollnos; names=names; fees=fees; >void displays() < System.out.println(rollnos+" "+names+" "+fees); >> class TestThis1 < public static void main(String args[]) < Students ss1=new Students(113,"amit",3000f); Students ss2=new Students(114,"sannit",4000f); ss1.displays(); ss2.displays(); >> 

The preceding example’s arguments (formal parameters) and object properties are identical. As a result, we’re utilizing this term to differentiate between local and instance variables.

Example:Students1.java

class Students1 < int rollnos; String names; float fees; Students1(int rollnos,String names,float fees) < this.rollnos=rollnos; this.names=names; this.fees=fees; >void displays() < System.out.println(rollnos+" "+names+" "+fees); >> class TestThiss2 < public static void main(String args[])< Students1 ss1=new Students1(113,"amit",98000f); Students1 ss2=new Students1(114,"sannit",56000f); ss1.displays(); ss2.displays(); >> 
113 amit 98000.0 114 sannit 56000.0 

There is no reason to use this term if variables (formal parameters) and example parameters are distinct, like in the following scheme:

This phrase is not necessary for this program.

Example: Students2.java

class Students2 < int rollnos; String names; float fees; Students2(int r1,String n1,float f1)< rollnos=r1; names=n1; fees=f1; >void displays() < System.out.println(rollnos+" "+names+" "+fees); >> class TestThis3 < public static void main(String args[])< Students2 ss1=new Students2(101,"amit",50010f); Students2 ss2=new Students2(102,"sannit",6200f); ss1.displays(); ss2.displays(); >> 
101 amit 50010.0 102 sannit 6200.0 

2) to call the current layer is responsible for managing

To use this keyword, one may call a method from the current group. If you do not include these keywords, the computer will add them for you when executing the procedure.

Example:A1.java

class A1 < void method() < System.out.println("hello students"); >void num() < System.out.println("hello name"); this.method(); >> class TestThiss4 < public static void main(String args[]) < A1 a1=new A1(); a1.num(); >> 
hello name hello students 

3) this(): invokes the current class’s function Object().

To invoke the current class function Object(), use the this() function Object() call. It allows you to reuse the function Object() . In other phrases, it serves to link constructors.

Читайте также:  Background size css javascript

Using the customizable function Object() to call the default function Object():

Example:A1.java

class A1 < A1()A1(int x1) < this(); System.out.println(x1); >> class TestThiss5< public static void main(String args[])< A1 a1=new A1(101); >> 

Using the generalized function Object() instead of the default function Object() :

Example:TestThiss6.java

class A11 < A11()< this(50); System.out.println("hello anne"); >A11(int x1) < System.out.println(x1); >> class TestThiss6 < public static void main(String args[])< A11 a1=new A11(); >> 

Actual implementation of the this() function Object() call

The this() function Object() call should be utilized to reuse the function Object() from the function Object(). It preserves the chain among constructors, i.e., it is utilised for function Object() concatenation. Let’s look at an example of how to utilise this keyword.

Example: TestThiss7.java

class Students11 < int rollnos; String names,courses; float fees; Students11(int rollnos,String names,String courses)< this.rollnos=rollnos; this.names=names; this.courses=courses; >Students11(int rollnos,String names,String courses,float fees) < this(rollnos,names,courses);// the constructor is used for recursing this.fees=fees; >void displays() < System.out.println(rollnos+" "+names+" "+courses+" "+fees); >> class TestThiss7 < public static void main(String args[])< Students11 ss1=new Students11(111,"amit","javaProgramming"); Students11 ss2=new Students11(112,"sannit","javaProgramming",60000f); ss1.displays(); ss2.displays(); >> 
111 amit javaProgramming 0.0 112 sannit javaProgramming 60000.0 

Example:TestThiss8.java

class Students < int rollnos; String names,courses; float fees; Students(int rollnos,String names,String courses)< this.rollnos=rollnos; this.names=names; this.courses=courses; >Students(int rollnos,String names,String courses,float fees) < this.fees=fees; this(rollnos,names,courses);// returns the compile time error >void display() < System.out.println(rollnos+" "+names+" "+courses+" "+fees);>> class TestThiss8< public static void main(String args[])< Students ss1=new Students(111,"Suman","javaPrograming"); Students ss2=new Students(112,"Rakesh","javaProgramming",6000f); ss1.display(); ss2.display(); >> 
error: call to this must be the first statement in the constructor

4) to be passed as a parameter to the method

The term this can also be used as a parameter in a procedure. It is mostly used in event management.

Consider the following example:

Example: St2.java

class St2 < void method(St2 obj)< System.out.println("The method is used"); >void p1() < method(this); >public static void main(String args[]) < St2 ss1 = new St2(); ss1.p1(); >> 

This can be used as an argument in the following ways:

In event-driven (or) when we need to pass a reference to another class. It’s employed to reuse a single object across many operations.

5) to be passed as a parameter in the function Object() call

This keyword can also be sent to the function Object(). It comes in handy when we use the same object in numerous classes. Consider the following example:

Example:Al4.java

class B1 < A14 object; B1(A14 object)< this.object=object; >void displays() < System.out.println(object.da);// the data is displayed >> class A14 < int da=1098; A14()< B1 b1=new B1(this); b1.displays(); >public static void main(String args[]) < A14 a1=new A14(); >> 

6) This keyword may be used to return the present instance of the class

This keyword can be returned as a sentence by the procedure. In such a circumstance, the solution’s function returns must be of the specific class (non-primitive).

This grammar can be provided as just a declaration

Example of return type constructor

Example:Tests11.java

class A1 < A1 getA1()< return this; >void msgs() < System.out.println("Hi every one"); >> class Tests11 < public static void main(String args[])< new A1().getA1().msgs(); >> 

Demonstrating this keyword

Let us demonstrate that this keyword relates to the property in the existing class instance. We’re printing the insights regarding this program, and the result of both instances are identical.

Example:A15.java

class A15 < void method()< System.out.println(this);// the reference id is then printed >public static void main(String args[]) < A15 object=new A15(); System.out.println(object);// the result is reference id object.method(); >> 

Источник

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 .

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=

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