Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism of variables

 
mo gillis
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way to inherit a variable that may be either a primitive or an object? Example:

abstract class Test {
String name;
int probability;

int result; //this is the variable that is a problem

void calculateResult() {
//do something here
}
}

class AbcTest {
//result is okay as an int
}

class XyzTest {
//result needs to be a boolean
}

class PdqTest {
//result needs to be a string
}

etc...I am running a series of identification tests on unknown organisms. One manufacturer's test kit gives either a positive or negative result (kind of like one of those over-the-counter pregnancy tests...no maybes!) Another manufacturer's test kit may give a result that would be a string like "red" or "yellow" (possibly indicating the color of an organism that has been isolated and cultured).

I would like any programmer who extends the Test class to know that they *have* to provide a result and its methods. I don't know what form the result for a particular test set will take (boolean, int, array, etc). I considered using Object or ArrayList, but thought this may be a problem with a primitive (yeah, I could use wrappers). Any thoughts ranchers?

Thanks,
Mo
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could have a TestResult interface, and different implementations with different content. For working on a specific result, you could either put polymorphic methods on it, or use the Visitor design pattern.

What exactly do you need to do with the test results?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic