Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force abstract method to execute predefined code - similar to overloaded return statement

I have a abstract class with a abstract method

 public abstract class Foo{
    public int bar();
}

This is inherited and implemented by normal classes using some methods.

public class ConcreteFoo1 extends AbstractFoo{
    public void bar(){
    method1();
    method2();
    closingMethod();
    return 1;

} }

public class ConcreteFoo2 extends AbstractFoo{
public void bar(){
    method3();
    method4();
    closingMethod();
    return 2;

} }

As you can see both classes end with closingMethod(); To end the implemented bar()method with the same line(s) is essential for a framework I work on. Is there a way to enforce that through the parent class. Lacking better words making it "semi abstract" where the first n lines are defined in the child class and the closing lines are defined by the parent. Ideally I would like to overload the return statement or implement a "method destructor".

Is there a way to achieve this?

like image 813
Einar Sundgren Avatar asked Apr 16 '26 02:04

Einar Sundgren


1 Answers

I would probably do it by defining a non abstract method in Foo in which I would call the abstract method bar and the closingMethod(), e.g.

public abstract class Foo {
    public void foo() {
        bar();
        closingMethod();
    }
    public abstract void bar();
}

UPDATE after OP's edit:

Indeed that complicates things a little, however you might do something like

public abstract class Foo {
    public int foo() {
        bar();
        closingMethod();
        return baz();
    }
    protected abstract void bar();
    protected abstract int baz();
}
like image 85
radoh Avatar answered Apr 17 '26 15:04

radoh