IntelliJ IDEA 2018.3 Help

Extract Field

The Extract Field refactoring lets you declare a new field and initialize it with the selected expression. The original expression is replaced with the usage of the field.

  1. Place the cursor within a piece of code you want to extract into a field.

  2. Press Ctrl+Alt+F or on the main menu, select Refactor | Extract Field.

  3. Select an expression you want introduce as a field.

    extract field
    If IntelliJ IDEA detects more than one occurrence in your code, it lets you specify which occurrences to replace.
    extract field occurrences
    Extract multiple occurrences of a field
    You can press Ctrl+Alt+F twice to open the Extract Field dialog where you can specify additional details, such as visibility options, or options for initializing your variable.
    extract field dialog


Let's extract the anotherClass.intValue(); variable into a field. As a result, IntelliJ IDEA changes the selected variable name to number and declares it as the private int number field.



public class Class { AnotherClass anotherClass; public void method() { int a = 1; int b = a + anotherClass.intValue(); int c = b + anotherClass.intValue(); } }

public class Class { public AnotherClass anotherClass; private int number; public void method() { int a = 1; number = anotherClass.intValue(); int b = a + number; int c = b + number; } }




class Hello def greet puts "Hello from JetBrains" end def bye puts "Goodbye from JetBrains" end end

class Hello def initialize @name = "JetBrains" end def greet puts "Hello from #{@name}" end def bye puts "Goodbye from #{@name}" end end

Last modified: 1 February 2019

See Also