2

For example I have two classes.

public class PActivity {
...
    @Override
    public boolean OnEventSocket(PMSocketEvent a_iEvent)
        ...
        handled = OnEventSocket(...);
    }
}

Second class:

public class PMenu extends PActivity {
    @Override
    public boolean OnEventSocket(PMSocketEvent a_iEvent)
    {
        ...
    }
}

How can I block the calling method from the second class?

Sometimes I want call the method OnEventSocket from the base class.

I have many classes like PMenu, so I have to make the change in PActivity

Michael
  • 41,989
  • 11
  • 82
  • 128
asus9e
  • 23
  • 6

1 Answers1

1

I would use a kind of template method pattern.

Essentially, rather than have an overridable public method, you override a protected method which is called by the public method. This allows you to do whatever checks you need to before invoking the overridden method.

public class PActivity {
...
    public final boolean onEventSocket(args)
    {
        if (method_should_be_called)
        {
            eventSocketImpl(args);
        }
    }

    protected boolean eventSocketImpl(args)
    {
        // default behaviour
    }
}

public class PMenu extends PActivity {
    @Override
    protected boolean eventSocketImpl(args)
    {
        // overridden behaviour
    }
}

You should be able to make this work without changing any of your PMenu implementations, with two drawbacks:

  • You will have a public method which should be protected
  • You will have to keep the current method names as they are, which may be confusing.
Michael
  • 41,989
  • 11
  • 82
  • 128
  • But I have I think 30 classes like PMenu, so I must change name OnEventSocket to eventSocketImpl everywhere? – asus9e Apr 05 '17 at 07:27
  • I want to avoid this situation – asus9e Apr 05 '17 at 07:35
  • @asus9e This is what I meant by my final two bullet points. You *could* keep it as it is now but that would mean your "entry point" method (my `public` one) would need to change name. Depending on how many places in the code this is called, this may be more or less work than changing all of your `PMenu`s. – Michael Apr 05 '17 at 09:04
  • 1
    Okay, I understand :) Thanks :) This function i call only once in PActivity – asus9e Apr 05 '17 at 09:22