简体   繁体   English

如何使用相同的变量名实例化不同类的对象

[英]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 . 在上面的代码中,我需要将obj分配给EnvAEnvB对象EnvB Because i will use only obj in my entire "class main". 因为我将在整个“ class main”中仅使用obj

You should define an interface having the create() method, and both EnvA and EnvB should implement it. 您应该定义一个具有create()方法的接口, EnvAEnvB都应实现它。

Then the type of obj would by the type of that interface. 然后obj的类型将obj该接口的类型。

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. 请注意,为了在您的main方法中引用obj ,它应该是类的静态成员或main方法的局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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