简体   繁体   中英

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".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM