Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

abstract class method suggestion

 
manish ahuja
Ranch Hand
Posts: 312
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a current design which is something like this.

Abstract class
---------------
public abstract void method1(Model obj);

public void method2(Model obj)
{
*** method2 logic goes here****
}
---------------
All sub classes inheriting the above abstract class will provide a custom implementation for method1. method2 is dependent on completion of method1 as the Model obj is first worked upon by method1 and only then method2 should happen. This is our business flow logic.
There could be many such child classes so after providing an implementation to method1 I will have to specifically invoke method2 as part of the implementation of method1.
I want to avoid this verbosity of invoking method2 every time from method1 and modularize the same as part of the abstract class.
Like say if we slightly reverse the above scenario where method2 is abstract and method1 is a concrete implementation retaining the same sequence of method call I could simply have declared the abstract class like this
Abstract class
---------------
public void method1(Model obj)
{
****custom logic***
method2(obj);
}

public abstract method2(Model obj);

---------------
and avoid the additional method call in each implementing sub class.

Is there a way out or alternative. Do suggest.

-MA
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The abstract class should have a public non-abstract method called method1() that looks like this:



The new method customLogic() should be abstract and protected; it's what a subclass has to override. By making it protected, you're clearly marking it as something that shouldn't generally be called by clients. Likewise, I used "final" to indicate that method1() shouldn't (can't) be overridden, so that method2() is always going to be invoked after the custom logic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic