Has some real use when implementing non-abstract methods in an abstract class

Asked

Viewed 158 times

5

Have some real use when implementing a method that has a field, (implemented code) in an abstract class that cannot be instantiated, since no compilation error occurs?

public abstract class ClasseAbstrata {

        //metodo não implementado projetado para ser sobreescrito 
        abstract void metodoAbstrato();

        public void metodoNaoAbstrato(){
            System.out.println("Real impleentação de código em uma classe abstrata");
        }
    }

1 answer

8


Yes, totally, most of the methods you want a class to have are usually implemented, you already know what you want it to do.

You are probably thinking the other way around, and citing compilation error strengthens this idea, after all giving compilation error has nothing to do with this concept.

Think of the abstract class as a normal class that happens to have some method that should not have an implementation. Leaving a method without implementation should be the exception and not the rule. In fact most abstract classes should not even have an abstract method.

People don’t understand object orientation. Yet they insist on using it. OOP is not about mechanisms, it’s about concepts. People think that a class should be abstract because it has an abstract method, but this kind of class should exist for one simple reason: this class should not be instantiated. This is the correct use of this mechanism, not because there is no other way to do what you want.

It turns out that if the class cannot be instantiated, by chance it allows an extra facility, some method can be without implementation that causes no problem, then one can gain an extra facility.

Forget the idea that abstract class should have abstract methods, this is a side effect. Even interfaces today can already have implementations, and in many cases should be designed for methods to have implementations.

I return the question: why do you want a method not to have implementation? You need a strong reason to do this.

You asked for real use, but gave an example not real. Real use depends on a real example. Anyway the real use has nothing to do with the mechanism of abstraction, the real use depends on its necessity and should not be driven by the mechanism. Programming is taking a problem to solve, not taking a mechanism and trying to force yourself into solving the problem. So people give exaggerated value to design patterns, when they should value correct concepts and simple solutions that solve a real problem.

  • That said, a quick example is the Template Method project pattern.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.