Partial implementation of an abstract method? - java

For example, I have many classes that all need a certain method.
In this method, all these classes need one line of code, the remainder of the method is different.
How could I achieve something like this:
void method(){
everybodyDoesThisStuff;
// more individual stuff
// more individual stuff
}
Abstract methods cannot have a body, and if you were not to make it abstract you would then override the method and lose it.

You should make the method that does the "more individual stuff" abstract, not the method itself.
// AbstractBase.java
public abstract class AbstractBase {
public final void method() {
everybodyDoesThisStuff();
doIndividualStuff();
}
abstract void doIndividualStuff();
private void everybodyDoesThisStuff() {
// stuff that everybody does
}
}
// ConcreteClass.java
public class ConcreteClass extends AbstractBase {
void doIndividualStuff() {
// do my individual stuff
}
}

One solution is to require all subclasses to call super.method(). The problem is that there's no way to actually enforce that. Another option is to create a separate method that internally executes the required line and then calls an abstract method:
public final void method() {
callEveryTime();
doMethod();
}
protected abstract void doMethod();
Note that method() is public final so it can be called anywhere but not overridden, whereas doMethod() is protected so it can be overridden but not called outside its package (or subclasses).

You can make a normal method call an abstract method:
void foo(){
// do stuff
bar(); // let the abstract method do the rest
}
abstract void bar();

If you're asking yourself whether you need partial implementations of an abstract method, it's usually time to reconsider the granularity of your design.
Why not extract everybodyDoesThisStuff into a separate method and put it in an Interface?

Related

How to force a subClass to implement a method in superClass which has body

Class Base{
public void doThings(){
//some logic that needed by subclass
}
}
Class A extends Base{
public void doThings(){
super.doThings();
doOtherThings();
}
}
What I want is to force A to overwrite doThings() method(there will be error message if not) and call super.doThings(); but doThings() in Base should not be abstract for it has body.
Is there any decent solutions? I found the same question in below link but the accepted answer does not answer it right.
Force SubClasses to #Override method from SuperClass. Method in SuperClass must have body
If you want to make sure that doThings of the base class is called, you should design your class like this:
abstract class Base {
public void doThings() {
// do some things here
...
// make sure subclass does some things too
methodYouMustImplement();
}
abstract void methodYouMustImplement();
}
class A extends Base {
#Override void methodYouMustImplement() {
// do some other things
}
}
This way, A is forced to give a implementation of methodYouMustImplement() and it is guaranteed by design that your code in doThings() is called without the need to remember to call super.doThings().
You could then consider making doThings() final, as Andy Turner suggested.
I think it would be easier to use a construct such as:
public class Base {
public void doStuff() {
doSpecificStuff();
// do base stuff every one has to do
}
abstract void doSpecificStuff();
}
public class WeirdlySpecific extends Base {
public void doSpecificStuff() {
// specific stuff happens
}
}
This does not force WeirdlySpecific to actually implement the doStuff() method, but as long as doStuff() is called as a contract by any caller, each more specific implementation has its own version of events.
A requirement to call the super method is considered an anti-pattern; that aside, the only way you can force a subclass to implement a method is to make it abstract.
If you want super.doThings() to be called first, and then subclass-specific stuff to be run after, turn the problem around:
Make doThings() final
Add an abstract method that is called within doThings().
Something like this:
abstract class Base {
public final void doThings() {
methodYouMustImplement();
// Stuff after subclass-specific implementation.
}
abstract void methodYouMustImplement();
}
class A extends Base {
#Override void methodYouMustImplement() {
doOtherThings();
}
}
The fact that doThings() is final is important to the requirements: this guarantees that the things you want to happen when doThings() is invoked, because no subclass can change this method. If you leave it non-final, subclasses can decide to override doThings(), meaning that methodYouMustImplement() (and any other actions you specify in doThing()) are not necessarily called.

Define and execute partial functions of an interface

I am new to Java so i have some obvious (to some of you) questions about declaration, definition and execution of some functions.
Suppose you have declared two methods in an interface and you want to define the behavior of the first function in a (abstract?) class and the second function in another (abstract?) class.
Is there a way to define two methods in two separate classes? For example i could have a lot of methods in an interface but I want to implement just one of them because a specific object does not needs the others. How can I do that??
Java Code example :
interface DeclareFcnts {
void foo1();
void foo2();
}
abstract class Define_fcn1 implements DeclareFcnts {
public void foo1() {
// TODO Auto-generated method stub
}
}
abstract class Define_fcn2 implements DeclareFcnts {
public void foo2() {
// TODO Auto-generated method stub
}
}
class Myclass {
public static void main(String args[]) {
// How can i create an object that reference to the first function only?
}
}
If you implement an interface in a class, you must assume it will have all the interface methods declared. You must define what happens if any of these methods are invoked. Consider this:
DeclareFcnts instance = new Define_fcn1();
instance.foo2(); // what happens here?
What is your expected behavior on the second line? It could throw an exception, do nothing, (or return a value if the method wasn't void).
One option is to define the behavior in the concrete implementing class (because you cannot instantiate abstract classes), which is what you would like to avoid. Fortunatelly, in Java 8, there is another way - using default methods:
interface DeclareFcnts {
default void foo1() { /* default implementation, e.g. throw or do nothing */ }
default void foo2() { /* default implementation, e.g. throw or do nothing */ }
}
class Define_fcn1 implements DeclareFcnts {
public void foo1() { /* do something */ }
}
In this case, Define_fcn1 will inherit implementation of foo2 from DeclareFcnts much like if it inherited from a super class. You can notice that the class no longer needs to be abstract.
That said, you should try to avoid such situations. They will make unit testing, refactoring, etc., more difficult. You may possibly split your interface into multiple interfaces. If you need both methods somewhere, you can pass the interfaces separately, or, if absolutely necessary, define another interface like this:
interface Foo1Iface { void foo1(); }
interface Foo2Iface { void foo2(); }
interface BothIface extends Foo1Iface, Foo2Iface { }
I would avoid it if possible, though. You may get more suggestions if you add more details to your answer.
AFAIK it is not possible, when you are implementing an interface you are obliged to #override those methods in that interface but you can leave it as blank assuming that you would not call it. Although:
This is your Generic interface, it can be anything as long as you meet the requirements.
Credits to Pinterest.
If you are going to design a house it does not make sense to add a wheel or anything unrelated to the house. Otherwise create a separate Interface for a Car or a Bus.
An Example of Bad Design
interface GenericInterface{
public void defineDoor();
public void defineWindow();
public void defineWheel();
}
The actual implementation
class House implements GenericInterface{
#Override
public void defineDoor{
// do something
}
#Override
public void defineWindow{
// do something
}
#Override
public void defineWheel{
// does not make sense to the House.
}
}
Here is another class that implements the Generic Interface
class Car implements GenericInterface{
#Override
public void defineDoor{
// do something
}
#Override
public void defineWindow{
// do something
}
#Override
public void defineWheel{
// do something.
}
}
Though our Car fits the above Interface but since when did the House contains a wheel?. The right way to do this is to create Separate Interface for Car and House.
You can not do this!
you must declare body for your method that declared in interface and then create instance of class
or you can use java 8 default declaration for your interface methods
for example:
public interface IX
{
void sayHello();
void sayBye();
default void showInfo()
{
System.out.println("you call show Info method");
}
}

Provide implementation for abstract method but restrict visibility

I have a method in an abstract class that calls an abstract method, for which the subclasses must provide the implementation.
public abstract class AClass {
public void foo() {
...
fooToImplement();
...
}
// DON'T CALL THIS METHOD, ONLY PROVIDE IMPLEMENTATION!
protected abstract void fooToImplement();
}
I want to make sure that the subclasses don't call fooToImplement(), they should always use foo() instead. The behavior is something like a "private abstract" method, but that's not possible in Java.
Is there some alternative? Thanks!
If you don't want your subclasses to be able to call this method you could use strategy: Extract the behavior of the method into an interface and pass an implementation of this interface to the object. E.g.
IStrategy {
public void fooToImplement();
}
AClass {
public AClass(IStrategy impl) {...}
public void foo() {
...
strategy.fooToImplement();
...
}
}
Delegation instead of inheritance. In java 8 this would be a little bit easier.
If your implementation of IStrategy would need access to the data of the object AClass, you could try to implement it as an inner class.
The method has to be visible by your subclass if you want it to be overriden.
You have to use a class witch does not extends AClass as caller.
public class BClass extends ACLass {
#Override
protected void fooToImplement() {
System.out.println("override me im famous");
}
}
public class CClass {
private BCLass bInstance;
public void doSomething(){
bInstance.foo();
// !!! NO ACCESS TO fooImplement()
}
}
Since fooToImplement() needs to be visible to subclasses to be implemented there and there's no way to distinguish between "implement visibility" and "execution rights", you can't do this by inheritance.
You could however combine your object with another object that contains fooToImplement() by composition:
interface FooImplementation {
void fooToImplement(AClass a);
}
public abstract class AClass {
private final FooImplementation fooImpl;
protected AClass(FooImplementation fooImpl) {
this.fooImpl = fooImpl;
}
public void foo() {
...
fooImpl.fooToImplement(this);
...
}
}
That wouldn't prevent anyone from outside the class from using yourFooImpl.fooToImplement(yourAClass) however. To prevent this you could create a class that provides the information that fooToImplement() needs, but that can only be instanciated from within AClass:
interface FooImplementation {
void fooToImplement(AClass.AClassFooView a);
}
public abstract class AClass {
private final FooImplementation fooImpl;
protected AClass(FooImplementation fooImpl) {
this.fooImpl = fooImpl;
}
public class AClassFooView {
...
private AClassFooView() {
}
}
public void foo() {
...
fooImpl.fooToImplement(this.new AClassFooView());
...
}
}
But fooToImplement could pass the reference to AClassFooView to other classes...
However depending on the implementors of your class making absolutely sure in the documentation, that nobody should call fooToImplement() could also be an alternative.
Ultimately you have to trust the implementors, since there's also the the possibility of someone using reflection to get access to private members, reverse engeneering+changing+recompiling your class ect..
You can use AOP to this, for example add aspect #Before to fooToImplement() and check stacktrace of calling and throw IllegalArgumentException if fooToImplement() be called any method except foo(), something like:
if(!Thread.currentThread().getStackTrace()[1].getMethodName().equals("foo")) {
throw new IllegalArgumentException("You musn't call fooToImplement() directly"+
", using foo() instead");
}
However this way has two problem:
perfomance
runtime exception

How to use abstract methods linked with enforced call for other methods

I am facing the following problem:
I defined an abstract class that contains the public generate, clone, etc. methods that must be implemented by the subclass. However I would like to ensure that when these public methods are called certain other methods are also executed within the abstract class.
An obvious solution would be to make a protected abstract method to be implemented and a public non-abstract method that calls the abstract one and all the other methods that I need.
For example:
abstract class Representation {
public void generate(int variable) {
myFunction();
generateAbstract(variable);
}
protected abstract void generateAbstract(int variable);
private void myFunction() {
//do something
}
}
My question is how to solve it a nicer way, or if this is the way to go how to name the function in a user-friendly way.
Thanks!
Your way of solving this issue is so standard that it even has a name: it is called Template Method Pattern. The idea is to provide a public method that executes the steps of your algorithm at high-level, and use overrides of protected abstract methods in subclasses to deal with lower-level steps of the algorithm. This is the correct way of addressing the problem.
I would do it as you are doing it. I would make the wrapper method either
final so I can't be blown away in a subclass, or
document the hell out of the methods, indicating that the abstract method MUST be called...
#dasblinkenlight's answer identifies the design pattern that addresses your problem: Template Method. I like this Template Method link more than the wikipedia entry that answer references. Also, I like answers with code examples:
// Demonstrate the template method design pattern
// straight out of GoF example
abstract class AbstractClass {
// Final ensures extender does not override, but depends on your design
final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
}
// document extenders should keep as protected
// so clients do not call directly
protected abstract void primitiveOperation1();
protected abstract void primitiveOperation2();
}
public class ConcreteClass extends AbstractClass {
#Override
protected void primitiveOperation1() {
System.out.println("ConcreteClass.primitiveOperation1()");
}
#Override
protected void primitiveOperation2() {
System.out.println("ConcreteClass.primitiveOperation2()");
}
}
I think your suggested method is quite elegant enough. I've certainly solved the same problem in this way before. I'd possibly call your method doGenerate() (or something without the word Abstract in it).
I think the easiest way to do this would be to ensure that super.generate is called. Since Java doesn't have a good mechanism for informing a class of when it has been subclassed (others like Ruby do), there's not much you can do to force a subclass that implements an abstract method to call another method.
As pointed out before, what you suggested is the correct approach according to the Template method pattern. What is left is the naming issue. I would not call the function to be overwritten "generateAbstract" because when it is implemented it is not abstract anymore. I recommend something like "makeGenerate()" which reflects the original function and implies what it does.
abstract class Representation {
public void generate(int variable) {
myFunction();
makeGenerate(variable);
}
protected abstract void generateAbstract(int variable);
private void myFunction() {
//do something
}
}
public class ConcreteClass extends Representation {
#Override
protected void makeGenerate() {
...
}

super.super.func()? - Java polymorphism

Say that I in Java have 3 classes, wheres the super one has a function named func(), I now make a subclass which overrides this, and a subclass to my subclass, now working on my sub-sub-class how will I call the 'func()' of the sub class, and the superclass?
I tried casting the 'this' "pointer", but Java 'fixes' it at runtime and calls the subsub func().
Edit:
Thanks everyone; 'Skeen is back at the drawing board'.
The best you can do is call super.func() in your subsub class, and have the func() implementation in your subclass also call super.func().
However, ask yourself, if I need knowledge not only of my parents implementation but also my grandparents implementation, do I have a design problem? Quite frankly this is tripping my "Something stinks in the fridge" instinct. You need to re-evaluate why you want to do this.
This isn't possible in Java. And btw. there aren't any pointers in Java.
I would jump on the "something in this design smells funny" train. Normally, you override a method so that it works properly for that specific subclass. If you have code in your parent class that is shared across multiple subclasses, perhaps that code could be moved to a non-overridden method so that it is readily accessible by all children/granchildren/etc.
Could you perhaps flip your design over and use more of a template method approach? (http://en.wikipedia.org/wiki/Template_method_pattern)
The notion behind Template Method is that you have some algorithm in your parent class and you can fill in the pieces that need to be class specific by polymorphic calls into your subclasses. You don't have a ton of detail in your question, but by the sounds of things, I'd really take a good look at your design and see if it makes sense.
Why don't you have func() be not inherited (call it funcBase() or whatever) and then add a wrapper func() function that calls it?
class A{
public void funcBase() {
// Base implementation
}
public void func() {
funcBase();
}
}
class B extends A{
public void func(){
super.func();
}
}
class C extends B{
public void foo(){
super.func(); // Call B's func
funcBase(); // Call A's func
}
}
I have no idea what you're trying to do, but it sounds like your class design is not appropriate for what you want, so you may want separate functions in A instead of trying to sneak your way up the ladder.
This example is the only way to call a "grandparent" super method.
class A{
public void foo(){ System.out.println("Hi"); }
}
class B extends A{
public void foo(){ super(); }
}
class C extends B{
public void foo(){ super(); }
}
This would be a different story if B doesn't override foo().
Another option would be to have a "protected helper" method in the middle class.
class D{
public void foo(){ System.out.println("Hi"); }
}
class E extends D{
public void foo(){ System.out.println("Hello"); }
protected void bar(){ super.foo(); }
}
class F extends E{
public void foo(){ super.bar(); }
}
You can access the superclass methods from within the subclass itself, e.g.
class A {
void foo() {...}
}
class B extends A {
void foo() {...}
void defaultFoo() { super.foo(); }
}
However, you really shouldn't be exposing overridden methods this way, you should write B.foo() in such a way that works fine for A and B. This is where it is a good idea to use super.foo(); like this:
class B extends A {
void foo() {
super.foo(); //call superclass implementation first
... //do stuff specific to B
}
}
Update: In response to your comment on trying to access the implementation 2 levels up, here's a way of doing it.
class A {
void foo() {
defaultFoo();
}
protected void defaultFoo() { ... }
}
class B extends A {
void foo() {...}
}
class C extends B {
void foo() {
defaultFoo();
... //do other stuff
}
}
This is a healthier pattern of coding what you want to do.
You should probably rethink how you are handling your class hierarchy if you need to place a call to a function that is defined two levels up the hierarchy. Consider writing new methods that are implemented by each subclass in a different way.

Categories