0

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

but usually this is a sign of a questionable code design. - so why do it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.