Question

I was wondering if there is a way to stop one class from using a method but let another use the method depending on what they extend.

Lets say class1 implements Plugin and class2 implements Mod, is it possible to allow class2 to use method load(); but stop class1 from using it

Was it helpful?

Solution

Maybe you can pass the type of the caller to the method and then use the instanceof comparison operator. For example:

public void myMethod(Object obj){
    if(obj instanceof Mod){
        \\ do something
    } else if(obj instanceof Plugin){
        \\ do not permit
    }
}

OTHER TIPS

Use instanceof to check the type of instance, and then give it the permission to method.

Class1 c1 = new Class1();
Class2 c2 = new Class2();

doIt(c1);
doIt(c2);

public void doIt(Object obj){

    if (obj instanceof Class2){

         myRestrictedMethod();

    }


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top