Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically add private qualifier to fields in eclipse

Tags:

java

eclipse

Is there a way to automatically add the private qualifier while new variables are declared in Eclipse?

In a way I would like to override the default access to private

like image 495
akd Avatar asked Aug 04 '13 10:08

akd


1 Answers

I don't know of a way to do this.

However, the way i write code, it would rarely be necessary. That's because i rarely define fields by hand; instead, i let Eclipse create them, and when it does that, it makes them private.

Say i want to create a class Foo with a single field bar of type int. Start with:

public class Foo {
}

Put the cursor in the class body, hit control-space, and choose 'default constructor' from the proposals menu. You now have:

public class Foo {
    public Foo() {
        // TODO Auto-generated constructor stub
    }
}

Delete the helpful comment. Now manually add a constructor parameter for bar:

public class Foo {
    public Foo(int bar) {
    }
}

Now put the cursor on the declaration of bar and hit control-1. From the proposals menu, choose 'assign parameter to new field':

public class Foo {
    private final int bar;

    public Foo(int bar) {
        this.bar = bar;

    }
}

Bingo. You now have a private field.

There is a similar sequence of automatic operations which can create a field from an existing expression in a method (first creating a local variable, then promoting it to a field).

like image 94
Tom Anderson Avatar answered Nov 03 '22 23:11

Tom Anderson