File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Polymorphism of variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Polymorphism of variables" Watch "Polymorphism of variables" New topic

Polymorphism of variables

mo gillis

Joined: Aug 25, 2005
Posts: 1
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 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?

Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
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?

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link:
subject: Polymorphism of variables
It's not a secret anymore!