User
User

Reputation: 363

Dynamicaly set class instance variable in java

Hi I am working on a project which has a variable which is an instance of the class. The problem is that depending on which option the user picks the instance variable can be on of the classes.

How can I assign a variable to an instance of a class when it can be 1 class or another class?

For example,

//I don't know if this variable is going to be of type class 1 or class 2 
//at this point any suggestions?

Class1 var1;

if(x == true)
{
  var1 = new Class1
}
else
{
  var1 = new Class2
}

Thanks in advance!

Upvotes: 0

Views: 57

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

Ideally, you should define some interface which both Class1 and Class2 implement. So, for example, your Class1 definition might look like this:

public class Class1 implements MyInterface {
    // ...
}

One nice way to handle your original question is to use a factory pattern:

public class ClassFactory {
    public static MyInterface getClass(boolean type) {
        if (x) {
            return new Class1();
        }
        else {
            return new Class2();
        }
    }
}

Then, give some boolean input, you may obtain the correct instance using:

boolean b = true;
MyInterface correctClass = ClassFactory.MyInterface(b);

The factory pattern is one of many design patterns which are available to structure your code in a good way, and make problems like this easier to solve.

Upvotes: 2

gsprs
gsprs

Reputation: 80

You can defined your variable as

Object var1;
if(x == true)
{
     var1 = new Class1();
}
else
{
    var1 = new Class2();
}

and then cast it later on when needed

if(var1 instanceof Class1){
    Class1 v = (Class1)var1;
    // ...
} else if(var1 instanceof Class2){
    Class2 v = (Class2)var1;
    // ...
} 

but usually this is a sign of a questionable code design.

Upvotes: 1

Related Questions