0

I have two classes that extends a third class, i.e.

public class class_a extends parent_class

and

public class class_b extends parent_class

My question is it possible to have a third class to create a reference to a class based on condition? i.e.

public void test() {
  parent_class b;
  if (cond)
    b = new class_a();
  else
    b = new class_b();
}

Is there a way to do that?

I don't want to create variables per type of class, I will only use one throughout the life time of this function.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Sharon
  • 88
  • 6

2 Answers2

3

That is exactly what the factory design pattern is for.

http://en.wikipedia.org/wiki/Factory_method_pattern

This might also be of use Factory Pattern. When to use factory methods?

Community
  • 1
  • 1
John3136
  • 28,809
  • 4
  • 51
  • 69
0

Yes. Polymorphism allows you threat subclass as base class. So, you can write method with parent_class return value type, like so:

parent_class create(boolean condition)
{
   return condition ? new class_a() : new class_b();      
}

As @John answered, it is called Factory method.

P.S. In Java, you better should name classes using CamelCase, like ClassA and ParentClass. Code style.

Seagull
  • 13,484
  • 2
  • 33
  • 45