This java что это

от admin

Классы. Объектно-ориентированное программирование

Java является объектно-ориентированным языком, поэтому такие понятия как «класс» и «объект» играют в нем ключевую роль. Любую программу на Java можно представить как набор взаимодействующих между собой объектов.

Шаблоном или описанием объекта является класс , а объект представляет экземпляр этого класса. Можно еще провести следующую аналогию. У нас у всех есть некоторое представление о человеке — наличие двух рук, двух ног, головы, туловища и т.д. Есть некоторый шаблон — этот шаблон можно назвать классом. Реально же существующий человек (фактически экземпляр данного класса) является объектом этого класса.

Класс определяется с помощью ключевого слова сlass :

В данном случае класс называется Person. После названия класса идут фигурные скобки, между которыми помещается тело класса — то есть его поля и методы.

Любой объект может обладать двумя основными характеристиками: состояние — некоторые данные, которые хранит объект, и поведение — действия, которые может совершать объект.

Для хранения состояния объекта в классе применяются поля или переменные класса. Для определения поведения объекта в классе применяются методы. Например, класс Person, который представляет человека, мог бы иметь следующее определение:

В классе Person определены два поля: name представляет имя человека, а age — его возраст. И также определен метод displayInfo, который ничего не возвращает и просто выводит эти данные на консоль.

Теперь используем данный класс. Для этого определим следующую программу:

Как правило, классы определяются в разных файлах. В данном случае для простоты мы определяем два класса в одном файле. Стоит отметить, что в этом случае только один класс может иметь модификатор public (в данном случае это класс Program), а сам файл кода должен называться по имени этого класса, то есть в данном случае файл должен называться Program.java.

Класс представляет новый тип, поэтому мы можем определять переменные, которые представляют данный тип. Так, здесь в методе main определена переменная tom , которая представляет класс Person. Но пока эта переменная не указывает ни на какой объект и по умолчанию она имеет значение null . По большому счету мы ее пока не можем использовать, поэтому вначале необходимо создать объект класса Person.

Конструкторы

Кроме обычных методов классы могут определять специальные методы, которые называются конструкторами . Конструкторы вызываются при создании нового объекта данного класса. Конструкторы выполняют инициализацию объекта.

Если в классе не определено ни одного конструктора, то для этого класса автоматически создается конструктор без параметров.

Выше определенный класс Person не имеет никаких конструкторов. Поэтому для него автоматически создается конструктор по умолчанию, который мы можем использовать для создания объекта Person. В частности, создадим один объект:

Для создания объекта Person используется выражение new Person() . Оператор new выделяет память для объекта Person. И затем вызывается конструктор по умолчанию, который не принимает никаких параметров. В итоге после выполнения данного выражения в памяти будет выделен участок, где будут храниться все данные объекта Person. А переменная tom получит ссылку на созданный объект.

Если конструктор не инициализирует значения переменных объекта, то они получают значения по умолчанию. Для переменных числовых типов это число 0, а для типа string и классов — это значение null (то есть фактически отсутствие значения).

После создания объекта мы можем обратиться к переменным объекта Person через переменную tom и установить или получить их значения, например, tom.name = «Tom» .

В итоге мы увидим на консоли:

Если необходимо, чтобы при создании объекта производилась какая-то логика, например, чтобы поля класса получали какие-то определенные значения, то можно определить в классе свои конструкторы. Например:

Теперь в классе определено три коструктора, каждый из которых принимает различное количество параметров и устанавливает значения полей класса.

Консольный вывод программы:

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

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

В третьем конструкторе параметры называются так же, как и поля класса. И чтобы разграничить поля и параметры, применяется ключевое слово this:

Так, в данном случае указываем, что значение параметра name присваивается полю name.

Кроме того, у нас три конструктора, которые выполняют идентичные действия: устанавливают поля name и age. Чтобы избежать повторов, с помощью this можно вызвать один из конструкторов класса и передать для его параметров необходимые значения:

В итоге результат программы будет тот же, что и в предыдущем примере.

Инициализаторы

Кроме конструктора начальную инициализацию объекта вполне можно было проводить с помощью инициализатора объекта. Инициализатор выполняется до любого конструктора. То есть в инициализатор мы можем поместить код, общий для всех конструкторов:

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.

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.

What is the meaning of "this" in Java?

I understand that it is used to identify the parameter variable (by using this.something ), if it have a same name with a global variable.

However, I don’t know that what the real meaning of this is in Java and what will happen if I use this without dot ( . ).

Ivar's user avatar

22 Answers 22

this refers to the current object.

Each non-static method runs in the context of an object. So if you have a class like this:

Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the this denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.

this is used to refer the constructors

This invokes the constructor of the same java class which has two parameters.

this is used to pass the current java instance as parameter

Similar to the above this can also be used to return the current instance

Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.

this can be used to get the handle of the current class

Though this can be done by

As always, this is associated with its instance and this will not work in static methods.

luk2302's user avatar

MicSim's user avatar

To be complete, this can also be used to refer to the outer object

It refers to the current instance of a particular object, so you could write something like

Читать:
Скрипт и макрос в чем разница

A common use-case of this is to prevent shadowing. Take the following example:

In the above example, we want to assign the field member using the parameter’s value. Since they share the same name, we need a way to distinguish between the field and the parameter. this allows us to access members of this instance, including the field.

Quoting an article at programming.guide:

this has two uses in a Java program.

1. As a reference to the current object

The syntax in this case usually looks something like

This type of use is described here: The ‘this’ reference (with examples)

2. To call a different constructor

The syntax in this case typically looks something like

aioobe's user avatar

In Swing its fairly common to write a class that implements ActionListener and add the current instance (ie ‘this’) as an ActionListener for components.

It’s «a reference to the object in the current context» effectively. For example, to print out «this object» you might write:

Note that your usage of «global variable» is somewhat off. if you’re using this.variableName then by definition it’s not a global variable — it’s a variable specific to this particular instance.

It refers to the instance on which the method is called

The this Keyword is used to refer the current variable of a block, for example consider the below code(Just a exampple, so dont expect the standard JAVA Code):

Thats it. the Output will be «2». If We not used the this keyword, then the output will be : 0

Balaji's user avatar

Objects have methods and attributes(variables) which are derived from classes, in order to specify which methods and variables belong to a particular object the this reserved word is used. in the case of instance variables, it is important to understand the difference between implicit and explicit parameters. Take a look at the fillTank call for the audi object.

The value in the parenthesis is the implicit parameter and the object itself is the explicit parameter, methods that don’t have explicit parameters, use implicit parameters, the fillTank method has both an explicit and an implicit parameter.

Lets take a closer look at the fillTank method in the Car class

In this class we have an instance variable «tank». There could be many objects that use the tank instance variable, in order to specify that the instance variable «tank» is used for a particular object, in our case the «audi» object we constructed earlier, we use the this reserved keyword. for instance variables the use of ‘this’ in a method indicates that the instance variable, in our case «tank», is instance variable of the implicit parameter.

The java compiler automatically adds the this reserved word so you don’t have to add it, it’s a matter of preference. You can not use this without a dot(.) because those are the rules of java ( the syntax).

  • Objects are defined by classes and have methods and variables
  • The use of this on an instance variable in a method indicates that, the instance variable belongs to the implicit parameter, or that it is an instance variable of the implicit parameter.
  • The implicit parameter is the object the method is called from in this case «audi».
  • The java compiler automatically adds the this reserved word, adding it is a matter of preference
  • this cannot be used without a dot(.) this is syntactically invalid
  • this can also be used to distinguish between local variables and global variables that have the same name
  • the this reserve word also applies to methods, to indicate a method belongs to a particular object.

Instance variables are common to every object that you creating. say, there is two instance variables

Say for instance you are trying to access object.field from inside of your class in say, your constructor for example, you could use

The this keyword essentially replaces the object name keyword when being called inside of the class. There usually isn’t much of a reason to do this outside of if you have two variables of the same name one of which being a field of the class and the other just being a variable inside of a method, it helps decipher between the two. For example if you have this: (Hah, get it? this? Hehe . just me? okay 🙁 I’ll leave now)

That would cause some problems, the compiler wouldn’t be able to know the difference between the Name variable defined in the parameters for the constructor and the Name variable inside of your class’ field declarations so it would instead assign the Name parameter to. the value of the Name parameter which does nothing beneficial and literally has no purpose. This is a common issue that most newer programs do and I was a victim of as well. Anyways, the correct way to define this parameter would be to use:

This way, the compiler knows the Name variable you are trying to assign is a part of the class and not a part of the method and assigns it correctly, meaning it assigns the Name field to whatever you put into the constructor.

To sum it up, it essentially references a field of the object instance of the class you are working on, hence it being the keyword «this», meaning its this object, or this instance. Its a good practice to use this when calling a field of your class rather than just using the name to avoid possible bugs that are difficult to find as the compiler runs right over them.

Ключевое слово THIS в Java

Ключевое слово THIS – это ссылочная переменная в Java, которая ссылается на текущий объект.

Ниже перечислены различные варианты использования ключевого слова «this» в Java:

  • Может использоваться для ссылки на переменную экземпляра текущего класса;
  • Может использоваться для вызова или запуска текущего конструктора класса;
  • Может быть передан как аргумент в вызове метода;
  • this может быть передано в качестве аргумента в вызове конструктора;
  • Может использоваться для возврата текущего экземпляра класса.

Примеры

ключевое слово THIS

Давайте скомпилируем и запустим код.

Наш ожидаемый результат для A и B должен быть инициализирован значениями 2 и 3 соответственно.

Но значение равно 0, почему? Давай подумаем.

вывод

В методе Set data аргументы объявляются как a и b, а переменные экземпляра также именуются как a и b.

аргументы a и b

Во время выполнения компилятор запутался. Является ли «a» слева от назначенного оператора переменной экземпляра или локальной переменной. Следовательно, он не устанавливает значение ‘a’ при вызове набора данных метода.

проверка

Решением является ключевое слово “this”

Добавьте оба «a» и «b» с ключевым словом «this», за которым следует оператор точки (.).

использование ключевого слова

Во время выполнения кода, когда объект вызывает метод ‘setdata’. Ключевое слово ‘this’ заменяется обработчиком объекта “obj.” (См. Изображение ниже).

выполнение

Итак, теперь компилятор знает,

  • ‘A’ в левой части является переменной Instance.
  • Принимая во внимание, что ‘a’ на правой стороне является локальной переменной

Переменные инициализируются правильно, и отображается ожидаемый результат.

инициализация

Предположим, вы достаточно умны, чтобы выбирать разные имена для вашей переменной экземпляра и аргументов методов.

создание объекта класса

Но на этот раз вы создаете два объекта класса, каждый из которых вызывает метод набора данных.

Как компилятор определит, должен ли он работать с переменной экземпляра объекта 1 или объекта 2.

работа компилятора

Что ж, компилятор неявно добавляет переменную экземпляра с ключевым словом «this» (рисунок ниже).

объект 1 вызывает метод набора данных

Таким образом, когда объект 1 вызывает метод набора данных, к переменной экземпляра добавляется его ссылочная переменная.

объект 2 вызывает метод набора данных

Пока объект 2 вызывает метод набора данных, переменная экземпляра объекта 2 изменяется.

завершение

Этот процесс заботится самим компилятором. Вам не нужно явно добавлять ключевое слово this, если нет исключительной ситуации, как в нашем примере.

Пример: чтобы узнать, как использовать this ключевое слово:

Шаг 1) Скопируйте следующий код в блокнот.

Шаг 4) Сохраните, скомпилируйте и запустите код. На этот раз значения ab установлены на 2 3 соответственно.

Похожие статьи