user826323 user826323 - 5 months ago 13
Java Question

java - unique difference between abstract class and concrete class

I know few differences between abstract class and concrete class. I know that you can't create an instance with abstract class unlike concrete class, abstract class can have 'abstract' methods.

But i have an example like the following. A lot of times, we see the following examples at work. I will just skip some common methods that can be defined in the Parent class.

public abstract class Parent {
public void init() {
doInit();
}
public abstract void doInit();
}

public class Child extends Parent {
public void doInit() {
// implementation
}
}


I think that we can do the same thing with a concrete class like the following.

public class Parent {
public void init() {
doInit();
}
public void doInit() {
// Empty
}
}


I am curious to see if there is any unique situation that we have to use abstract class. Is there any significant difference during runtime with the above example?

Thank you.

Answer

The reason to use abstract class in this situation is to force everyone inheriting your base class to override the abstract doInit method. Without the class and the method being abstract, they may forget to do so, and the compiler would not catch them.

In addition to this pragmatic purpose, abstract classes provide a powerful way to communicate your design idea to the readers of your code. An abstract class tells the reader that the methods inside provide some common implementation for a group of related classes, rather than implementing a single concept that you are modeling. Very often communicating your intent to your readers is as important as it is to write correct code, because otherwise they might break something while maintaining your code.

It is customary in Java to call abstract classes Abstract...; in your example that would be AbstractParent.

Comments