We use abstract classes if we need to keep an implemented method and method definitions while we use interfaces if we need to keep just the method definitions. But in java and C# we can use default methods and static methods to include implementations in interfaces. So what is the use of abstract classes if we can achieve what it is intended to do by using interfaces?
-
Does this answer your question? When to use: Java 8+ interface default method, vs. abstract methodjaco0646– jaco06462022-07-28 14:12:38 +00:00Commented Jul 28, 2022 at 14:12
-
Also see additional answers to the query: stackoverflow.com/questions/tagged/…jaco0646– jaco06462022-07-28 21:47:58 +00:00Commented Jul 28, 2022 at 21:47
Add a comment
|
1 Answer
There are some reasons to have abstract classes.
Abstract classes can inherit interfaces, but not vice versa
Abstract classes can inherit interfaces. However, interface cannot inherit abstract class:
public interface ABar { }
public abstract class Bar : IFoo { }
However, this is not eligible:
public interface IFoo : ABar
{
}
public abstract class ABar
{
}
Abstract classes can have constructors, fields (can hold state)
Abstract classes can have constructors, fields. By having fields, it is possible to hold state. However, interface cannot have them.
public abstract class ABar
{
public int test; // some state
public ABar()
{
}
}