Home > Mobile >  Achieve polymorphism without touching the base class
Achieve polymorphism without touching the base class

Time:12-01

I have the following class hierarchy:

public abstract class Root {
    ...
}

public class A extends Root {
    ...
}

public class B extends Root {
    ...
}

public class C extends Root {
    ...
}

I want to apply a function func on objects of static-type Root, so that the behavior of the function will be dependent on the specific dynamic-type.

So obviously I can accomplish it using polymorphism. I could create an abstract function inside Root and implement it differently in every class that extends Root.

However, what if the code of Root is inaccessible and I can't edit it? The only solution I could think of is to implement func inside A, B and C separately, and then do something like this:

public static void applyFuncOnRootObject(Root object) {
    if (object instanceof A) {
        ((A) object).func()
    } else if (object instanceof B) {
        ...
    }
    ...
}

Is there a better solution that avoids the ugly casting and if-statements?

CodePudding user response:

You could create your own Root class.

public class MyRoot extends Root{
     public void func(){}
}

And make classes A, B and C extends MyRoot instead of Root

  • Related