7

I would like to do something like this:

if (condition)
    super(foo.class);
else
    super(bar.class);

But the super constructor has to be the first in the constructor. Is it possible to do this anyway?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eko
  • 1,487
  • 1
  • 18
  • 36

1 Answers1

13

Assuming you're calling the same superconstructor in both cases and just passing in a different argument, you can just use the conditional operator:

super(condition ? Foo.class : Bar.class);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Is there something wrong if we pass the Class object to the super constructor and then let the super class handle it like if(condition) do something. else, do something else ?. – TheLostMind May 02 '14 at 08:41
  • @WhoAmI: That's a very general question - we have no idea of the context here. It also sounds like a different question. – Jon Skeet May 02 '14 at 08:48
  • But wouldn'nt it make more sense to put the conditional check in the place / method where the variable is supposed to be used?. – TheLostMind May 02 '14 at 08:49
  • 2
    @WhoAmI: not necessarily. That code may have no idea what the condition is, or the options. It may do in some cases, but we don't have enough information to say in this case. – Jon Skeet May 02 '14 at 08:52
  • ya.. your approach is obviously better. I don't think the super class needs to worry about how to handle different classes. thanks :) – TheLostMind May 02 '14 at 08:56