Pradeep Simha
Pradeep Simha

Reputation: 18123

Query regarding overriding in Java

Consider I have a interface like this:

public interface Test {
  //Basically life cycle methods
  public void beforeStart(); 
  public void start();
  public void end();
}

And there is a abstract class, which provides basic or empty implementations for all of the methods.

public abstract class TestAdapter implements Test {
   //Implementations here
}

So that clients extending TestAdapter, can override one, or all of the life cycle methods. I am mandating each consumer should extend TestAdapter class and they can override all or one or none of the lifecycle methods in TestAdapter.

But the problem is each consumer of TestAdapter creates an instance of a POJO class for which life cycle should be managed ie beforeStart() etc.

My question is:

  1. There is no problem if client overrides all of the life cycle methods, but if he don't override anyone of the method, I should be able to execute default services for that particular life cycle method and for which I need reference to the user created POJO in testAdapter implementation class. How can I proceed to implement this??
  2. As you are aware this is somewhat similar to servlet's life cycle. So can anyone guide me? Or Am I complicating my design?

Please let me know if you need more clarifications regarding same.

Edit: Note: If you feel I am trying to re-invent wheel, can you kindly suggest any alternative for above requirements?

Upvotes: 1

Views: 114

Answers (3)

Adam Arold
Adam Arold

Reputation: 30528

First I think that you should use annotations as you can see in most test frameworks:

@BeforeClass
public void beforeClass() {
  // code here
}

@BeforeMethod
public void beforeMethod() {
  // code here
}

If you really want to stick with inheritance you can do something like this:

public abstract class TestAdapter implements Test {

    private AbstractPojo myPojo;

    protected void doBeforeStart(){
        // do something which you always want to happen
        beforeStart();
    } 
    protected void doStart() {
        start();
    }
    protected void doEnd() {
        end();
    }

    // your empty implementations of Test here

    // getter and setter for myPojo
}

In this case you can control internally what should happen and let your users override the methods in the interface as they see fit.

Upvotes: 1

Santosh
Santosh

Reputation: 17893

This problem is of "Creating an object step by step". This is solved by a Builder Pattern.

Here is another example in java for implementing Builder pattern.

Upvotes: 1

GingerHead
GingerHead

Reputation: 8230

You can have an argument in the method to control the POJO object.
On the other hand, there are a lot of ready frameworks to use instead of creating your own, why invent the wheel again?

Upvotes: 1

Related Questions