Question

It has been asked 100 times, but they all have different answers. so I dare put this question again. Why we can't move all the abstract method to interface?

I know there is template pattern which can be implemented using abstract method, but then it can be done using Interface as well, so why abstract method at all. Today I am reading about this and trying to find answer.

Thanks in advance.

Was it helpful?

Solution

An interface defines a public contract for an object. I often use protected (in Java) abstract methods when using the template pattern because I don't want outside callers to be able to call the method.

There are possibly cases where you might not want an interface. What if you had something like

abstract class MyClass {
     someConreteMethod() { ... }
     abstract someAbstractMethod();
}

Maybe you only want implementations of MyClass to extend the abstract MyClass

In general, I don't frequently use public abstract methods, but having non-public ones is much more common.

OTHER TIPS

I'm assuming you know this already but, interfaces require that the implementer overwrite the every method. Abstract classes do not. The reason this is useful is because you might want to provide one, method implementation to all the classes that extend that abstract class.

A trivial example might be a Person class

abstract class Person{

public void pumpBlood(){
//do blood pumping stuff 
}

public void talk(); 
public void getDressed(Clothes someClothes); 
}

all people should (in theory) pump blood in the same way but not all should getDressed or talk the same way. Abstract classes are good for situations like this where a concrete method may be provided.

This is an example of Template method pattern. A template made with an abstract class, with some finals method (logic that you dont want to be changed), and abstract methods(to de overriden by implementations)

public abstract class HtmlTemplate {

    /**
     * Get html code.
     * Its final, so nobody can override.
     * @return Html code.
     */
    public final String getHtml() {
        String html = "<html>"
                + "<head>"
                + getHead() // abstract method
                + "</head>"
                + "<body>"
                + getBody() // abstract method
                + "</body>"
                + "</html>";
        return html;

    }

    /**
     * Get head implementation.
     * @return head code
     */
    protected abstract String getHead();

    /**
     * Get body implementation.
     * @return body code
     */
    protected abstract String getBody() ;
}

public class MyHtmlPageImpl extends HtmlTemplate {

    @Override
    protected String getHead() {
        return "<title>My page</title>";
    }

    @Override
    protected String getBody() {
        return "Hello world";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top