Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract method restriction control for derived classes

Is it possible for an abstract base class to have abstract methods where only certain derived classes have access to certain abstract methods? What I'm trying to do is limit possible methods being able to be called from different inherited classes. Here is an example of my question:

public abstract Foo
{
    ...
    public abstract void fooMethod1(int num1);
    public abstract void fooMethod2(int num2);
}

public Bar1 extends Foo // This class shouldn't be able to access fooMethod2()
{
    ...
    @Override
    public void fooMethod1(int num1)
    {
        System.out.println((num1 * 5));
    }
}

public Bar2 extends Foo // This class has no restrictions
{
     ...
     @Override
     public void fooMethod1(int num1)
     {
          System.out.println((num1 * 10));
     }

     @Override
     public void fooMethod2(int num2)
     {
          System.out.println((num2 * 5));
     }

1 Answers

All your public abstract methods must be override in every sub class. What yo can do:

  1. Split Foo abstract class to two classes: BaseFoo and ExtendedFoo where ExtendedFoo should extends BaseFoo, so Bar1 extends BaseFoo and Bar2 extends ExtendedFoo.
  2. Override the unwanted method to throw UnsupportedOperationException so if this method is called it will throw a (meaningful) exception.

I would go with first approach.

like image 158
BobTheBuilder Avatar answered Sep 03 '26 23:09

BobTheBuilder