0

I've just recently stumbled upon this when trying to simplify my class' constructors that have about 50% of identical codes. It seems like I couldn't re-use my former constructor definition (which handles initialization) from another constructor that overloads it.

For the sake of clarity, this is what I've been trying to say:

public MusicOrganizationHelper(Context context) 
{
    mContext = context;
    // More object initializations using 'context'..
}

public MusicOrganizationHelper(Context context, ArrayList<String> fileUris) 
{
    MusicOrganizationHelper(context); // Why can't I do this?

    for (String uri : fileUris) {
        if (uri != null && !uri.equalsIgnoreCase("")) {
            try {
                AudioFile audioFile = read(uri);
                mAudioFileMap.put(audioFile, audioFile.getTagOrCreateAndSetDefault());
            } catch (CannotReadException e) {
                e.printStackTrace();
            }
        }
    }
}

I know this could be easily produced by making some sort of private void init(context) method but I'm just curious: why can't I call constructors like any other method even from within its class definition? They seems pretty similar to me (them constructors and 'peasant' methods).

I'm sorry if this turns out to be an obvious thing. I'm relatively new to Java and OOP in general.

Thanks in advance!

2
  • 4
    this(context)....? Commented Nov 23, 2014 at 11:00
  • See any sources of java (e.g. HashMap, ArrayList). And you will see how they handle it. Commented Nov 23, 2014 at 11:01

1 Answer 1

2

Replace this

MusicOrganizationHelper(context); // Why can't I do this?

with

this(context);

That's the way to invoke one constructor from another constructor of the same class. Note that this must be the first line of the constructor.

The first statement of a constructor body may be an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.7.1).

(JLS)

Sign up to request clarification or add additional context in comments.

2 Comments

Slaps face. I'm sorry, I don't know that it would be this simple. Accepted.. in 10 minutes time (gotta obey the rules).
..and could you provide an elaboration on why it has to be on the first line? Sorry if this is a bit too much to ask. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.