Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial implementation of an abstract method?

For example, I have many classes that all need a certain method. In this method, all these classes need one line of code, the remainder of the method is different.

How could I achieve something like this:

void method(){
    everybodyDoesThisStuff;

    // more individual stuff 

    // more individual stuff
}

Abstract methods cannot have a body, and if you were not to make it abstract you would then override the method and lose it.

like image 505
2ARSJcdocuyVu7LfjUnB Avatar asked May 16 '16 21:05

2ARSJcdocuyVu7LfjUnB


People also ask

Can an abstract method have an implementation?

An abstract method doesn't have any implementation (method body). A class containing abstract methods should also be abstract. We cannot create objects of an abstract class. To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass.

What is partial abstraction in Java?

In Java, abstract classes allow for partial to complete abstraction. Partial abstraction is achieved by having implementations with concrete methods. Full abstraction is achieved using interfaces with abstract types that specify a class' behavior.

What happens if abstract method is not implemented?

If abstract class doesn't have any method implementation, its better to use interface because java doesn't support multiple class inheritance. The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class.


1 Answers

You should make the method that does the "more individual stuff" abstract, not the method itself.

// AbstractBase.java
public abstract class AbstractBase {
    public final void method() {
        everybodyDoesThisStuff();
        doIndividualStuff();
    }

    abstract void doIndividualStuff();

    private void everybodyDoesThisStuff() {
        // stuff that everybody does
    }
}

// ConcreteClass.java
public class ConcreteClass extends AbstractBase {
    void doIndividualStuff() {
         // do my individual stuff
    }
}
like image 177
forrert Avatar answered Sep 26 '22 02:09

forrert