Arshad
Arshad

Reputation: 449

Can I initialize same variable name with different objects based on certain condition in java?

I have n number of objects and I need any one of them while execution based on certain condition. For Example.

switch(condition)
{
   case 1:
       Object1 obj = new Object1();
   break;
   case 2:
       Object2 obj = new Object2();
   break;
   default:
       defaultObject obj = new defaultObject();
   break;
}
int getItem = obj.getItemFromObject();

I am using the obj object in many other places in my code. I know the question may seem trivial or even stupid but please help me. Or guide me towards an alternative approach.

Upvotes: 2

Views: 2074

Answers (3)

rgamber
rgamber

Reputation: 5849

One way is to use a super class to declare a subclass variable. Eg. If you want an object of either class P, Q or R, then use a super class A.

P, Q, R will all extend A.

Here is some (untested) code:

A obj = null;
switch(condition)
{
   case 1:
       obj = new P();
       break;
   case 2:
       obj = new Q();
       break;
   default:
       obj = new R();
       break;
}

Upvotes: 0

Abubakkar
Abubakkar

Reputation: 15644

First of all, does this even compile? (I don't think it will compile at all)

You have declared your obj object inside switch, so it will complain duplicate local variable obj as you are having object with same variable name inside a single block.

Also it will not be able to find it when you invoke this (as it is outside its scope):

int getItem = obj.getItemFromObject(); it will complain obj cannot be resolved

Unless you have declared and initialzed obj somewhere before.

And of course, you can do initialize your object based on conditions you want, that's not a big deal.

Upvotes: 2

Anirudh
Anirudh

Reputation: 389

Score of variable declared inside switch's case statement corresponds to switch block. Hence, you can't re-declare same variable in different cases. However, you can assign same variable different values, depending upon case.

Object obj = null;
switch(condition)
{
   case 1:
       obj = new Object1();
   break;
   case 2:
       obj = new Object2();
   break;
   default:
       obj = new defaultObject();
   break;
}
int getItem = obj != null ? obj.getItemFromObject() : -1;

Upvotes: 1

Related Questions