Java: Reference to a type?

I need to instantiate an object of one of two different types, depending on a conditional. Both types take the same arguments to their constructors, and both are subclasses of a master type. Can I define a reference to the correct type inside the conditional and then instantiate the object using that reference? Quick example: if (v == "bob") { Object myType = bobType; } else { Object myType = otherType; } SuperType instance = new myType(arg1, arg2); This doesn't work; is there a correct syntax for this in java? This is as a shortcut to doing this: if (v == "bob") { SuperType instance = new bobType(arg1, arg2); } else { SuperType instance = new otherType(arg1, arg2); } I'm actually making several instances, all of the same type, that all take a long list of arguments, and I wanted to avoid exactly repeating myself except for the type.
everyone's answers are amazing; i wish i could accept more than one. i'm going to accept jacobm's because he explains the correct way to do something like this (although, yeah, it's a little verbose).

以上就是Java: Reference to a type?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏