Define this in java

this keyword in Java

this is a keyword in Java. It can be used inside the method or constructor of a class. It(this) works as a reference to the current object, whose method or constructor is being invoked. This keyword can refer to any member of the current object from within an instance method or a constructor.

this keyword with a field(Instance Variable)

this keyword in java can be handy in the handling of Variable Hiding. We can not create two instances/local variables with the same name. However, it is legal to create one instance variable & one local variable or Method parameter with the same name. In this scenario, the local variable will hide the instance variable; this is called Variable Hiding.

Example of Variable Hiding

class JBT < int variable = 5; public static void main(String args[]) < JBT obj = new JBT(); obj.method(20); obj.method(); >void method(int variable) < variable = 10; System.out.println("Value of variable :" + variable); >void method() < int variable = 40; System.out.println("Value of variable :" + variable); >>

The output of the above program

Value of variable :10 Value of variable :40

As you can see in the example above, the instance variable is hiding, and the value of the local variable (or Method Parameter) is displayed, not the instance variable. To solve this problem, use this keyword to point to the instance variable instead of the local variable.

Читайте также:  Real time program in java

Example of this keyword in Java for Variable Hiding

class JBT < int variable = 5; public static void main(String args[]) < JBT obj = new JBT(); obj.method(20); obj.method(); >void method(int variable) < variable = 10; System.out.println("Value of Instance variable :" + this.variable); System.out.println("Value of Local variable :" + variable); >void method() < int variable = 40; System.out.println("Value of Instance variable :" + this.variable); System.out.println("Value of Local variable :" + variable); >>

The output of the above program

Value of Instance variable :5 Value of Local variable :10 Value of Instance variable :5 Value of Local variable :40

this Keyword with Constructor

“this” keyword can be used inside the constructor to call another overloaded constructor in the same class. It is called the Explicit Constructor Invocation. This occurs if a Class has two overloaded constructors, one without argument and another with the argument. Then this” keyword can call the constructor with an argument from the constructor without argument. This is required as the constructor cannot be called explicitly.

Example of this with Constructor

class JBT < JBT() < this("JBT"); System.out.println("Inside Constructor without parameter"); >JBT(String str) < System.out .println("Inside Constructor with String parameter as " + str); >public static void main(String[] args) < JBT obj = new JBT(); >>

The output of the above program

Inside Constructor with String parameter as JBT Inside Constructor without parameter 

As you can see, “this” can invoke an overloaded constructor in the same class.

  • this keyword can only be the first statement in Constructor.
  • A constructor can have either this or super keyword but not both.

this Keyword with Method

this keyword can also be used inside Methods to call another Method from the same Class.

Example of this keyword with Method

class JBT < public static void main(String[] args) < JBT obj = new JBT(); obj.methodTwo(); >void methodOne() < System.out.println("Inside Method ONE"); >void methodTwo() < System.out.println("Inside Method TWO"); this.methodOne();// same as calling methodOne() >>

The output of the above program

Inside Method TWO Inside Method ONE

Example of this keyword as a Method parameter

public class JBTThisAsParameter < public static void main(String[] args) < JBT1 obj = new JBT1(); obj.i = 10; obj.method(); >> class JBT1 extends JBTThisAsParameter < int i; void method() < method1(this); >void method1(JBT1 t) < System.out.println(t.i); >> 

If you understood this keyword correctly, the next step should be to understand the Static Keyword in Java from Java Tutorial.

References
1- Official Document

Next Post
Java Static Keyword

70 thoughts on “this keyword in Java”

class car
int speed;
car()
speed=70;
>
protected void finalize()
System .out.println(“destroy object of car”);
>
>
class bike
int speed;
bike()
speed=70;
>
protected void finalize()
System.out.println(“destroy object of bike”)
>
>
class Garbage_Collection
public static void main(String []args)
car c=new car();
bike b=new bike();
b=null;
System.gc();
System.out.println(“speed of car: “+c.speed);
>
>

class JBT <
public static void main(String[] args) <
JBT obj = new JBT();
obj.methodTwo();
>
void methodOne() <
System.out.println(“Inside Method ONE”);
>
void methodTwo() <
System.out.println(“Inside Method TWO”);
this.methodOne();// same as calling methodOne()
>
> when I removed ‘this’ from the line this.methodOne();// same as calling methodOne() I get the same output. Is this the standard behaviour ?

Yes, that is standard behavior. this is just used to point to the current object and in this case, it is the current object’s method. So it will get called.

Источник

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=

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