Java – forces abstract methods to execute predefined code – similar to overloaded return statements

I have an abstract class of abstract methods

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

This is inherited and implemented by ordinary 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(); Ending the use of the peer - implemented bar () method is crucial to the framework I use There is no way to enforce through the parent class The lack of better words makes it "semi abstract", in which the first n lines are defined in the subclass and the end lines are defined by the parent class Ideally, I want to overload the return statement or implement the method destructor

Is there any way to achieve this goal?

Solution

I may implement it by defining a non abstract method in foo, which I call the abstract method bar and closingmethod(), for example,

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

Update after OP editing:

In fact, it can complicate things, but you may do something

public abstract class Foo {
    public int foo() {
        bar();
        closingMethod();
        return baz();
    }
    protected abstract void bar();
    protected abstract int baz();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>