apelsin
apelsin

Reputation: 55

Using different method depending on class in Java

I'm trying to reduce some code duplication. Currently i got two methods that are almost identical, the major difference being calling two separate methods within them.

Below is basically what i wanna do:

private void combinedMethod(StandardClass sc, MyClass mc)
{
    Method m = null;
    if(mc instanceof MySubClass1)
        m = sc.RelevantFor1();
    if(mc instanceof MySubClass2)
        m = sc.RelevantFor2();

    m(mc.getA(), mc.getB());
}

I've tested (and it works) this using reflection. But is there a better way of doing it? I read somewhere that reflection is slow and only to be used as a last resort. Is it in this case?

Also in this case the StandardClass is a standard class in the java api. The Class I send in is of my own making.

Upvotes: 3

Views: 197

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213281

It isn't clear how exactly those methods look like, or what they are doing, but it seems like a perfect polymorphism case. You can create a method in super class - MyClass I suppose in this case. And override those methods in your subclasses.

Now, when you call that method on MyClass reference, appropriate subclass method will be called based on actual instance. Now invoke whatever method you want to invoke in respective overridden methods.

Somewhere along the lines of:

class MyClass {
    public void method(StandardClass sc) { }
}

class MySubClass1 extends MyClass {
    public void method(StandardClass sc) {
        sc.method(getA(), getB());
    }
}

class MySubClass2 extends MyClass {
    public void method(StandardClass sc) {
        sc.anotherMethod(getA(), getB());
    }
}

And then your combinedMethod looks like:

private void combinedMethod(StandardClass sc, MyClass c) {
    c.method(sc);
}

Upvotes: 3

Related Questions