Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Is there a way to you enforce a implementation of private methods?

Tags:

java

oop

I have 5 or 6 classes that I want to have follow the same basic structure internally. Really most of those that the classes should follow are just for the use of the function itself, so I really want these methods to be private.

Is there any way to achieve this? I know interfaces would work great but they won't take private members and won't allow you to redefine the scope in the implemented method. Is there any workaround for this?

Thanks

like image 825
Matthew Stopa Avatar asked Dec 31 '09 17:12

Matthew Stopa


2 Answers

I think the closest you can get is using an abstract class with abstract protected methods:

abstract class A {
    protected abstract void foo();
}

class B extends A {
    protected void foo() {}
}

To define common logic, you can call the protected method from a private method in the super class:

abstract class A {
    private void bar() {
        // do common stuff
        foo();
    }
    protected abstract void foo();
}

This way, you can allow subclasses to fill the private common template method with specific behavior.

like image 104
Fabian Steeg Avatar answered Oct 11 '22 12:10

Fabian Steeg


Create an abstract base class that outlines the structure and common flow. Specify abstract methods for the steps in the flow that must be implemented by the inheriting classes.

like image 34
Paolo Avatar answered Oct 11 '22 12:10

Paolo