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
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.
Related
The question is considered as a general Object Oriented Design question and not related to any specific case for now.
Let's say I have a test library which has an abstract class:
public abstract class AbstractTest<E extends Event> {
private ProcessingService service = new ProcessingService();
protected static abstract void buildTestData();
public void testSomething(Event event) {
beforeScenario(event);
service.process(event);
// ... asserts and other actions
afterScenario(event);
}
protected void beforeScenario(E event) {
// override if needed
}
protected void afterScenario(E event) {
// override if needed
}
}
Each class derived from AbstractTest is forced to provide buildTestData() implementation and optionally could provide its own beforeScenario and afterScenario.
Having such empty methods has it's own pros and cons from my point of view. You don't make derived classes to #Override optional methods as opposed to abstract methods. Also you ensuring proper order of calling the scenarios in case when derived class overrides them and uses testSomething from abstract class:
public class SpecificTest extends AbstractTest<SomeEvent> {
protected static void buildTestData() {
// build test data
}
// override only scenarious and do not touch testSomething()
protected void beforeScenario(E event) {
// construct
}
protected void afterScenario(E event) {
// destroy
}
}
On the other hand these empty concrete methods look weird in parent class. Derived class can #Override testSomething like:
public class SpecificTest extends AbstractTest<SomeEvent> {
protected static void buildTestData() {
// build test data
}
// assuming that you don't have these methods in parent classes
public void testSomething(Event event) {
beforeScenario(event);
super.testSomething(event);
afterScenario(event);
}
private void beforeScenario(E event) {
// construct
}
private void afterScenario(E event) {
// destroy
}
}
Which approach is more appropriate from OOD point of view?
Does it make sense to to keep such empty methods in parent classes at all?
There is nothing wrong with your approach. Your code structure resembles that of a Template Pattern.
A template pattern implementation would look like (taken from Head First Design Patterns)
abstract class AbstractClass {
final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
concreteOperation();
hook();
}
abstract void primitiveOperation1();
abstract void primitiveOperation2();
final void concreteOperation() {
//implementation
}
void hook() { }
}
The primitiveOperations are abstract and must be overridden by the subclass whereas the concreteOperation is marked final and cannot be overridden.
We also have a concrete method called hook which does nothing by default. The subclasses can choose to override it or decide not to. These methods are called hooks.
So, when comparing your code with this
buildTestData is a primitiveOperation
testSomething is concreteOperation
beforeScenario and afterScenario are hooks
Here's the situation: I have a class and I create instances of. I'd like it to inherit the majority of the methods/variables in the class, but I want a few methods to be required to be overridden, similar to how an abstract class works.
Here is my code so far.
public class Example {
public void methodOne() {
//Inherited
}
public void methodTwo() {
//Interited
//Maybe calls methodThree() as a part of its function
}
public void methodThree() {
//Override Me
}
}
I can't [make the class abstract] because I need to create instances
Making the class abstract does prevent instantiation, but since you want to prevent instantiation unless a method is overridden, this is the right thing to do.
You can make overrides anonymously, so syntactically this would be similar to instantiating the base class:
public abstract class Example {
public void methodOne() {
//Inherited
}
public void methodTwo() {
//Interited
//Maybe calls methodThree() as a part of its function
}
public abstract void methodThree();
}
...
static void main(String[] args) {
Example e = new Example() {
#Override
public void methodThree() {
... // Do something
}
};
}
First of all, requiring people to write code in a particular way can be counter productive. Someone may have a legitimate use-case (that you had not considered !!) for dong it differently, and your restriction may force them to solve the problem in a way that makes things significantly worse than if your restriction wasn't there. Bear this in mind ...
But here's a solution:
public abstract class ExampleBase {
public void methodOne() {
// Inherited
}
public void methodTwo() {
// Interited
// Maybe calls methodThree() as a part of its function
}
public abstract void methodThree();
}
public final class Example {
#Override
public void methodThree() {
// Do stuff.
}
}
We have solved the problem by moving all of the members that you want to inherit to an abstract superclass. Any methods that you want to force people to override are declared as abstract. By declaring your concrete Example class as final, we prevent them from circumventing your requirement and subclassing Example without overriding methodThree.
This is a base class:
public abstract class BaseClass
{
protected void demoMethod()
{
//to Do
}
}
I want to test whether demoMethd() in sub class is called or not using Mockito.
I tried with Mockito.verify but call goes to sub class method but i want to super method to be called.Is there any solution to test whether super.demoMethod() is called or not. Code is given as below:
public class SubClass extends BaseClass
{
#Override
protected void demoMethod()
{
if( true)
{
return;
}
super.demoMethod();
}
}
According to me we can not call to protected method in Test class so therefore the things which i wanted is not possible for this case.
I have an abstract base class which looks like this:
public abstract class AbstractConfig {
public String someMethod(List<Params> params) {
if (inputValidationFails()) { /* sanity check of params */
return null;
}
return something;
}
}
And I have subclasses that perform the same input validation.
public class CustomConfig extends AbstractConfig {
#Override
public String someMethod(List<Params> params) {
if (inputValidationFails()) { /*same input validation code*/
return null;
}
return somethingElse;
}
}
How can I avoid having to implement this input validation in base class as well in every subclass?
Implementing [non-private] helper method inputValidationFails() inAbstractConfig and calling it in base class and in every sub class doesn't seem particularly good or clean.
I suggest you split your method into two separate method, one public method which you implement in your base class and a protected abstract method which is called by the other method and which is implemented in the sub classes.
This way you can implement things which apply to all subclasses in the base class and avoid code duplication. The resulting base class would look something like this:
public abstract class AbstractConfig {
public String doStuff(List<Params> params) {
if (performErrorChecks()) {
return doTheActualStuff(params);
}
return null;
}
protected abstract String doTheActualStuff(List<Params> params);
}
And the subclasses would just implement doTheActualStuff():
public class CustomConfig extends AbstractConfig {
#Override
protected String doTheActualStuff(List<Params> params) {
...
}
}
You can also declare doStuff() as final in AbstractConfig. This would additionally prevent any subclass from overriding doStuff() and accidentally replacing your common error checking.
I'm developing a java application using a certain library(included using a jar file), i want to override a method exists on a class(abstract class) contained in that library, or even change a certain parameter value in it.
Is there is a way to do that?
Extend the class from which you want to override the method.
public class ClassFromExtLib {
public void foo(Object param) {
}
}
public class MyClass extends ClassFromExtLib {
#Override
public void foo(Object param) {
super.foo(param);
//adding my own implementation...
}
}
If you can't extend the class, use a wrapper class that can execute the method and then add your own logic to it.
public final class ClassFromExtLib {
public void foo(Object param) {
}
}
public class MyClass {
//code to initialize the instance of the class ommited
private ClassFromExtLib bar;
public void foo(Object param) {
bar.foo(param);
//adding my own implementation...
}
public void foo(Object param, Object param2) {
bar.foo(param);
//adding my own implementation using param and param2...
}
}
If you want to add/remove parameters from the method, then you can't do this by an overriding, that's an overloading. The second way would be the best for you.
Yes and no. You can create a subclass which has the different behavior you want.
public class MyVersion extends JarVersion {
However if you change the signature, callers will typically ignore the change.
You can also use the delegate pattern.
public MyClass {
JarClass delegate;
public void myMethod(MyParm mp) {
JarParm jp = makeJPfromMP(mp);
extraStuff();
delegate.originalMethod(jp);
moreExtraStuff();
}
Its very simple,
Just create one another class that extends that class(assuming its extendable) for which you need modification
And then override the methods that you want to change.