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.
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.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With