Java intellij idea конструктор

Классы и объекты

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

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

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

Вся функциональность класса представлена его членами — полями (полями называются переменные класса) и методами. Например, класс Book мог бы иметь следующее определение:

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

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

Здесь у класса Book определено два конструктора. Первый конструктор без параметров присваивает неопределенные начальные значения полям. Второй конструктор присваивает полям класса значения, которые передаются через его параметры.

Читайте также:  Python len of file

Так как имена параметров и имена полей класса в данном случае у нас совпадают — name, author, year, то мы используем ключевое слово this . Это ключевое слово представляет ссылку на текущий объект. Поэтому в выражении this.name = name; первая часть this.name означает, что name — это поле текущего класса, а не название параметра name. Если бы у нас параметры и поля назывались по-разному, то использовать слово this было бы необязательно.

Мы можем определить несколько конструкторов для установки разного количества параметров и затем вызывать один конструктор из другого:

Источник

Generate code

IntelliJ IDEA provides multiple ways to generate common code constructs and recurring elements, which helps you increase productivity. These can be either file templates used when creating a new file, custom or predefined live templates that are applied differently based on the context, various wrappers, or automatic pairing of characters.

Additionally, IntelliJ IDEA provides code completion and Emmet support.

This topic describes ways to generate standard code constructs specific to Java: constructors, method overrides and implementations, getters and setters, and so on. From the main menu, select Code | Generate Alt+Insert to open the popup menu with available constructs that you can generate.

Here is a video that demonstrates how to generate various code constructs in IntelliJ IDEA:

Generate constructors

IntelliJ IDEA can generate a constructor that initializes specific class fields using values of corresponding arguments.

Generate a constructor for a class

  1. On the Code menu, click Generate Alt+Insert .
  2. In the Generate popup, click Constructor .
  3. If the class contains fields, select the fields to be initialized by the constructor and click OK .

The following code fragment shows the result of generating a constructor for a class:

Generate delegation methods

IntelliJ IDEA can generate methods that delegate behavior to the fields or methods of your class. This approach makes it possible to give access to the data of a field or method without directly exposing this field or method.

Generate a delegation method for a class

  1. On the Code menu, click Generate Alt+Insert .
  2. In the Generate popup, click Delegate Methods .
  3. Select the target field or method, and click OK .
  4. Select the desired methods to be delegated and click OK .

The following code fragment shows the result of delegating the get(i) method of the Calendar class inside another class:

Generate equals() and hashCode() methods

The Java super class java.lang.Object provides two methods for comparing objects:

  • public boolean equals(Object obj) returns true if the object passed to it as the argument is equal to the object on which this method is invoked. By default, this means that two objects are stored in the same memory address.
  • public int hashCode() returns the hash code value of the object on which this method is invoked. The hash code must not change during one execution of the application but may change between executions.

It is generally necessary to override the hashCode() method if you override equals() because the contract for hashCode() is that it must produce the same result for objects that are equal. For more information, see the API specification for the Object class.

Generate equals() and hashCode() for a class

  1. From the Code menu, click Generate Alt+Insert .
  2. In the Generate popup, click equals() and hashCode() .
  3. Select a velocity template from the Template list. You can also click to open the Templates dialog, where you can select an existing template or create a custom template.
  4. Select checkboxes if you want to accept subclasses and use getters during code generation.
  5. Click Next .
  6. Select the fields that should be used to determine equality, and click Next .
  7. Select the fields to use for calculating the hash code value. You can choose only from fields that were selected on the previous step (for determining equality). Click Next .
  8. Select the fields that contain non-null values. This optional step helps the generated code avoid checks for null and thus improves performance. Click Finish .

If the overrides for equals() and hashCode() methods already exist in the class, you will be prompted whether you want to delete them before generating new ones.

The following code fragment shows the result of overriding the equals() and hashCode() methods:

Generate getters and setters

IntelliJ IDEA can generate accessor and mutator methods ( getters and setters ) for the fields in your classes. Generated methods have only one argument, as required by the JavaBeans API.

The getter and setter method names are generated by IntelliJ IDEA according to your code generation naming preferences.

  1. On the Code menu, click Generate Alt+Insert .
  2. In the Generate popup, click one of the following:
    • Getter to generate accessor methods for getting the current values of class fields.
    • Setter to generate mutator methods for setting the values of class fields.
    • Getter and Setter to generate both accessor and mutator methods.
  3. Select the fields to generate getters or setters for and click OK . You can add a custom getter or setter method by clicking and accessing the Getter/Setter Templates dialog. If a field is not in the list, then the corresponding getter and setter methods are already defined for it.

The following code fragment shows the result of generating the getter and setter methods for a class with one field var :

Note for PHP

The following is only valid when the PHP plugin is installed and enabled.

In the PHP context, getters and setters are generated using the PHP Getter/Setter/Fluent setter file templates. By default, as specified in these templates, setters are generated with the set prefix, and getters with the is or get prefix according to the inferred property type – boolean or non-boolean . The prefix is the value of the $ variable in the default getter template. The templates are configured in the Code tab on the File and Code Templates.

Generate toString()

The toString() method of the Java super class java.lang.Object returns the string representation of the object. This method can be used to print any object to the standard output, for example, to quickly monitor the execution of your code. By default, toString() returns the name of the class followed by the hash code of the object. You can override it to return the values of the object’s fields, for example, which can be more informative for your needs.

Override the toString() method for a class

  1. On the Code menu, click Generate Alt+Insert .
  2. In the Generate popup, click toString() .
  3. Configure the following:
    • Select the template for generating the toString() method from the Template list.
    • Select the fields that you want to return in the generated toString() method. By default, all the available fields are selected. Click Select None to generate a toString() method that returns only the class name.
    • Select the Insert @Override checkbox if necessary.
    • Click the Settings button to open the toString() Generation Settings dialog. where you can tune the behavior and add custom templates.
  4. Click OK .

If the toString() method is already defined in the class, by default, you will be prompted whether you would like to delete this method before proceeding. You can use the When method already exists group of options in the toString() Generation Settings dialog to change this behavior: either automatically replace existing method or generate a duplicating method.

The following code fragment shows the result of generating the toString() method for a class with several fields defined:

The following code inspections are related to the toString() method:

  • Class does not override ‘toString()’ method can be used to identify classes in which the toString() method is not defined. This inspection uses the exclude settings to ignore classes with fields that are not supposed to be dumped. An additional setting is to exclude certain classes using a regular expression matching their class name. As default, this is used to exclude any exception classes.
  • Field not used in ‘toString()’ method can be used to identify fields that are not dumped in the toString() method. For example, if you added new fields to a class, but forgot to add them to the toString() method. Change the severity of this inspection to show errors as warnings. This will highlight any unused fields in the editor and indicate their location as yellow markers on the scroll bar.

Custom code generation templates

Templates used for generating getters and setters, as well as equals() , hashCode() , and toString() methods are written in the Velocity template language. Although you can’t modify predefined templates, you can add your own custom templates to implement necessary behavior.

IntelliJ IDEA provides the following variables for Velocity templates:

The following variables can be used in templates for generating getters and setters:

The current version of the Java Runtime Environment (JRE).

Provides access to various code generation helper methods.

Provides the ability to format names according to the current code style.

Field for which getter or setter is generated.

The following variables can be used in templates for generating the toString() method:

The current version of the Java Runtime Environment (JRE).

Provides access to various code generation helper methods.

Provides the ability to format names according to the current code style.

List of fields in the current class.

The following variables can be used in templates for generating the equals() method:

The current version of the Java Runtime Environment (JRE).

Provides access to various code generation helper methods.

Provides the ability to format names according to the current code style.

List of fields in the current class.

Predefined name of the object on which the equals() method is called.

Predefined name of the equals() method parameter.

The name of the parameter in the equals() method of the superclass if applicable.

Option passed from the wizard.

Whether the superclass has equals() declared.

The following variables can be used in templates for generating the hashCode() method:

The current version of the Java Runtime Environment (JRE).

Provides access to various code generation helper methods.

Provides the ability to format names according to the current code style.

List of fields in the current class.

Whether the superclass has hashCode() declared.

In IntelliJ IDEA Ultimate, the code completion popup is available for custom code generation template variables. Users of IntelliJ IDEA Community Edition can refer to the relevant source code.

Productivity tips

Use code completion

Depending on the current context, IntelliJ IDEA can suggest generating relevant code constructs in the code completion popup. For example, when the caret is inside a Java class, the completion popup will contain suggestions for adding getters, setters, equals() , hashCode() , and toString() methods.

Источник

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