0
public class Wrapper {

    public Wrapper(final String name, final String email) {

        _name= name;
        _email = email;
    }

    private static final Card testCard = new Card(_email, _name);

    private final static String _name;
    private final static String _email;
    }

I would like the instantiate this class providing a name and an email.

I am getting "Cannot reference a variable before it is defined for (_email, _name) variables on line :

    private static final Card testCard = new Card(_email, _name);

I can make it work by moving the declarations to the top but is there any other way?

Thanks

ecthelion84
  • 356
  • 2
  • 5
  • 14

2 Answers2

0

You cann't initialize static field because variables _email and _name are not initialized yet. You should initialize testCard after _email and _name will be initialized.

For example, you can do it in constructor

public Wrapper(final String name, final String email) 
{
    _name= name;
    _email = email;
    testCard = new Card(_email, _name);
}

private static Card testCard;

or separate method for it

public static void initialize(String name, String email)
{
    _name= name;
    _email = email;
    testCard = new Card(_email, _name);
}

Also you should remove final modifiers if you want to initialize static in contructor.

Ilya
  • 29,135
  • 19
  • 110
  • 158
0

Based on your description, I don't think you want to use static.

I would like the instantiate this class providing a name and an email.

That means that you provide a name and an e-mail when creating an instance of the class. But using static means that there is only one name and one e-mail, that all instances of the class share! Unless every person in your universe has the same name and the same e-mail address, that is not what you want. So get rid of static on _name, _email, and testCard.

Also, initializing testCard outside the constructor won't work, because the program will try to do new Card(_email, _name) before _email and _name have been initialized. So change that to

private final Card testCard;

and in the constructor:

testCard = new Card(_email, _name);

after _email and _name have been set.

If you do this, you should be able to put the declarations anywhere you want. The "Cannot reference a variable before it is defined" or "Illegal forward reference" problems only come up when you have global (static) variables, according to this question.

Community
  • 1
  • 1
ajb
  • 31,309
  • 3
  • 58
  • 84