Mathew Kurian
Mathew Kurian

Reputation: 6039

how to have dynamic method parameters

Lets say i have a method

public abstract void doMath(Holder h);

But I want the user to be able to adjust the class being passed in. Like such

public abstract void doMath(ClassOfPersonalChoice h);

How would I go about doing that.

Thank you for your time and effort.

PS: The class being passed contains a bunch of variables. ie.

class ClassofPersonalChoice{
    double hue = 0;
int R = 240;
int G = 10;
int B = 180;
}

Upvotes: 4

Views: 4019

Answers (2)

Andreas Dolk
Andreas Dolk

Reputation: 114777

If you say

public abstract void doMath(Object h);

then the user can implement whatever he wants.

Advanced idea: use generics/type parameters:

public abstract class MathClass<T> {

   public abstract void doMath(T holder);

}

public class IntegerMathClass extends MathClass<ClassOfPersonalChoice> {

    @Override
    public void doMath(ClassOfPersonalChoice holder) {
      // do something with the value
    }

 } 

Upvotes: 2

Bozho
Bozho

Reputation: 597106

If you declare the argument to be of type Object, you'd be able to pass anything. But you won't be able to do anything with it, because you don't know what type it is. That's the way statically-typed languages work.

Ideally, you should declare the argument to be of type SomeInterface, and all objects that you pass should be instances of classes implementing that interface. That way you will know what operations you can do on the objects, but you won't need to know their exact classes.

Upvotes: 2

Related Questions