You're not declaring it again. You're initializing it with the second bit of code -- big difference.
This is no different from any other reference variable. i.e.,
public class MyFoo {
private String fooString; // (A)
public MyFoo() {
fooString = "hello world"; // (B)
}
You could also declare it and initialize it on the same line.
public class MyFoo {
private String fooString = "hello world";
private JTextField textField = new JTextField(10);
public MyFoo() {
// now can use both variables
}
So the first statement (statement (A) in my String example above) in your code creates variable of type JTextField, but when created they are automatically filled with default values, which for reference variables (everything except for primitives such as ints, doubles, floats,...) is null
. So you have variables that refer to null or nothing, and before using them you must assign to them a valid reference or object, and that's what your second bit of code does (statement (B) in my String example above) .
You will want to run, not walk to your nearest introduction to Java tutorial or textbook and read up on variable declaration and initialization as you really need to understand this very core basic concept before trying to create Swing GUI's, or any Java program for that matter. It's just that important.