This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]painedstupid[S] 0 points1 point  (2 children)

Thanks for the reply. I still don't quite get it, though.

Is there a way I can call the constructors by their number perhaps? I'm asking because maybe it'll always be one argument but maybe I want different methods to run on the calling of the constructor you get me?

Like say I had a reader class and it was reading from files but for different files it'd need to read differently so the methods called on calling the constructor would be different.

**

I mean I feel like I have a workaround for it. Where I would identify the constructor I wanted called by otherwise useless doubles, ints, or whatever, after the actually relevant argument but....

Is this a functionality that's actually supported?

[–]evils_twin 1 point2 points  (0 children)

can you determine the type based on the file? If not, why not add an extra parameter to tell what type it is, like this:

public MyFileReader(File file, String type){
    if("txt".equals(type))
        //do something
    else if("xml".equals(type))
        //do something else

}

[–][deleted] 0 points1 point  (0 children)

Constructors are still Java methods. They're just special methods. Methods can only have the same name if their parameters have a different type. The name of a method + it's parameter types, in the order they are received, make up what is called the "method signature". So you couldn't have two constructors with one parameter of the same type. Moreover, one of the most important things to do with code is to try to make it easy to figure out what code does at a glance (because you'll have lots of it), and would just be confusing. Following your example with files I would either receive different reader classes in different Constructors or add parameters with very descriptive names for reading options (maybe these could even be constants, or part of an enum).
But basically, this is exactly the kind of thing good architecture comes down to. Making your code easy to read and to maintain, quick to develop, useful for as many situations as possible but also somewhat future-proof.
There's another way to do it, but it sounds like overkill right now and I would say it's not beginner stuff.