Praveen PS
Praveen PS

Reputation: 127

How to use same variable name to instantiate the object of different classes

I'm trying to create a reference variable with same name and assign class objects to the same depending on the environment. Please check the sample code below.

class EnvA{

public void create(){
.....
   }
}
class EnvB{

public void create(){
.....
  }
}

class main{
EnvA obj = null;
EnvB obj= null;
public static void main(string[] args)
    if(itisEnvB)
        obj  = new EnvA();
     else
         obj  = new EnvB();
    //create method should be called depending on which environment is set
    obj.create();
}

In the above code I need obj to get assigned to object refernce of either EnvA or EnvB. Because i will use only obj in my entire "class main".

Upvotes: 0

Views: 1594

Answers (1)

Eran
Eran

Reputation: 394156

You should define an interface having the create() method, and both EnvA and EnvB should implement it.

Then the type of obj would by the type of that interface.

public interface Createable
{
    public void create();
}

class EnvA implements Createable {...}

class EnvB implements Createable {...}

...

Createable obj = null;
if(itisEnvB) {
    obj = new EnvA ();
} else {
    obj = new EnvB ();
}
obj.create();

Note that in order to refer to obj in your main method, it should either be a static member of your class or a local variable of the main method.

Upvotes: 6

Related Questions