Why are interfaces preferred to abstract classes?
That interview question reflects a certain belief of the person asking the question. I believe that the person is wrong, and therefore you can go one of two directions.
- Give them the answer they want.
- Respectfully disagree.
The answer that they want, well, the other posters have highlighted those incredibly well.
Multiple interface inheritance, the inheritance forces the class to make implementation choices, interfaces can be changed easier.
However, if you create a compelling (and correct) argument in your disagreement, then the interviewer might take note.
First, highlight the positive things about interfaces, this is a MUST.
Secondly, I would say that interfaces are better in many scenarios, but they also lead to code duplication which is a negative thing. If you have a wide array of subclasses which will be doing largely the same implementation, plus extra functionality, then you might want an abstract class. It allows you to have many similar objects with fine grained detail, whereas with only interfaces, you must have many distinct objects with almost duplicate code.
Interfaces have many uses, and there is a compelling reason to believe they are 'better'. However you should always be using the correct tool for the job, and that means that you can't write off abstract classes.
Does a class which is extending an abstract class still has to implement the interface that abstract class is implementing?: java
Assuming ClassA
is not abstract
and fully implements ClassB
, then ClassC
inherits ClassA
's implementation and does not need to re-implement anything from ClassB
unless it wants to override the behavior.
It also does not need to specify implements ClassB
. The following example is valid:
public static interface I { }
public static class A implements I { }
public static class B extends A { }
public static void main(String[] args) {
I b = new B();
}
LinkedList in Java: Why it directly implements List when it indirectly from extended class
No, it has no impact in terms of language semantics in this case. I imagine they just put it to make it clearer that it implements List
as well, without the developer having to traverse the full hierarchy.
Related Topics
Converting an Array of Objects to an Array of Their Primitive Types
Parsing Xml with Regex in Java
Why Does This Go into an Infinite Loop
@Aspectj Pointcut for All Methods of a Class with Specific Annotation
How to Convert Ascii Code (0-255) to Its Corresponding Character
Spring Boot @Responsebody Doesn't Serialize Entity Id
Synchronizing on an Integer Value
How to Asynchronously Call a Method in Java
Why Is Java's Iterator Not an Iterable
Platform Independent Paths in Java
Java 8 Date and Time: Parse Iso 8601 String Without Colon in Offset
Is Httpsession Thread Safe, Are Set/Get Attribute Thread Safe Operations
Persistencecontext Entitymanager Injection Nullpointerexception