Java class this next

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 <в примерах 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 (этот) конструктор, который имеет два параметра.
  • и добавить недостающую переменную.
Читайте также:  Geocoding Service

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

This Keyword in Java

«This» keyword in java is one of the most used and very important keywords.
«This» keyword in java is used to refer current class objects.
We can use this keyword to access current class object members.

Image of boy for understanding this keyword in java

So you might be wondering if we can access the current class member directly, Why do we need this keyword?

One of the answer is that, if we have same name for method level and class level variable, then there is an ambiguity for JVM. JVM can not use class variable and uses the local variable by default. In such a case we can use «this» keyword for referring the class level variable.

6 uses of «this» keyword in java

  1. Accessing class level variable
  2. Accessing class methods — default
  3. For calling other constructor of same class
  4. Using ‘this’ keyword as return value
  5. Passing ‘this’ keyword as argument to method
  6. Passing this keyword as argument to constructor

1. Accessing class level variable

Assessing class level variable using this keyword is the most common use of «this» keyword.

Most of the time we create some variable in class, then we can set the value from constructor or setter method. If we use same name for argument variable and class level variable then jvm will use local variable always, and it will not set the value to class level variable

lets take a look at example for better understanding,

public class Country< private String name; public Country(String name)< Wrong: name = name; Right: this.name = name; data-lazy-src=

3. For calling other constructor of same class

«This» keyword in java can be used to call other constructor of same class.

Some times we have different constructors with different parameters then you can reuse existing constructor using «this» keyword.
We can call any type of constructor within any constructor. That is we can call default in parameterized, parameterized in defatul or parameterized in parameterized constructor.

The most important thing to note is that the use of «this» for calling other constructor should be the first line in constructor.

Let’s assume we have a class, let’s call it SomeClass. In this class we have a default constructor and a constructor with variable.
There is some default code that is required for at object creation. So we have added this code in default constructor.
Now we need the same code from default constructor in parameterized constructor. So in this case we can call default constructor from another constructor using this();

public class SomeClass < private int variable ; public SomeClass()< // some code. >public SomeClass(int variable ) < this() this.variable = variable ; >>

Lets take look at real life examples for shape class. In this class we have length and breadth variables. we need two constructors.
Fist constructor will take two arguments for length and breadth.
Second constructor will take only one argument, this will be same value for length and breath.

public class Shape < private int length ; private int breadth; public Shape(int length ,int breadth)< this.length = length ; this.breadth = breadth; >public Shape(int length ) < this(length,length); >>

In above examples we are reusing constructors using «this» keyword in java.

Читайте также:  Utf 8 code in javascript

4. Using «this» keyword as return value in java

If you need to return current object instance we can use «this» keyword.
Builder design pattern is one of the most common example of this case.

Let’s look at an example for better understanding,

public class MenuBuilder < Listmenus = new ArrayList<>(); public MenuBuilder withAdd() < menus.add(new Menus("Add")) return this; >>

As you can see in the above example, we used «this» as return value in withAdd() Method. In above example withAdd() method returns the current class object.

5. Passing «this» keyword as argument to method

If we want to call some method and the method needs current class object as argument, we can use this keyword to pass the current class object instance.

We can pass this as argument to current class as well as another class methods.

public class City < private String name; private Country country; public City(String name)< this.name= name; >public void setCountry(Country country) < this.country = country; >> public class Country < private City capital; public void setCapital(String cityName)< City capital = new City(cityName); // passing country class object using this keyword capital.setCountry(this); this.capital = capital; >>

As shown in the above example, we have City and Country class. In City class setCountry() method needs object of Country class. So we have passed Country class instance using «this» keyword from Country class.

6. Passing «this» keyword as argument to constructor

Similar to passing as argument to another method we can also pass «this» keyword as argument to constructor of another class.

We can pass this as argument to constructor of current class as well as to constructor of another class.

public class City < private String name; private Country country; public City(String name, Country country)< this.name= name; this.country = country; >> public class Country < private City capital; public void setCapital(String cityName)< // passing country class object using this keyword City capital = new City(cityName,this); this.capital = capital; >>

As shown in the above example, we have City and Country class. In City class constructor needs object of Country class. So we have passed Country class instance using «this» keyword from Country class.

Fast track reading

  • This keyword in java is used to refer current class objects
  • Using this keyword we can access current class instance variable, methods, or constructor
  • We can pass this keyword as argument to another method or constructor
  • We can return current class instance using this keyword

Related topics

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