Please note. This question is not an abstract class vs interface kind of question.
Yes. I know. It's not necessary for a class which extends an abstract class to override all of its unimplemented methods. If a child class is not giving definition to some of its parent's unimplemented methods, then child class will be also considered to be abstract.
But a class which implements an interface should implement all of its methods ( Also Multiple inheritance is possible with interfaces).
Is this the only difference between an abstract class with only abstract methods and an interface?
yes, I understand. An Abstract class can have states and method implementations. But I'm making the question very clear. Its not actually a interface vs abstract class kind of question.
Here, in the question, the abstract class is not having any data members or any method implementations. Just some abstract methods only. eg:
abstract class shape{
abstract void draw();
}
I just want to know whether there are any other differences. What should I use in such a scenario?
Please help.
I believe your question is not necessarily one vs the other but how to know which one to choose in an instance.
A way I like to think about it is that interfaces tend to be actions that are available to the user to interface with the class. For example, if a class implemented the interface playable you know it would have a play method, whether it be starting an audio player, starting video, or starting a game would depend on the class itself, but you just know it is a playable class and can play.
Whereas shape is not an action, it is a type, shape comes along with attributes to define it, you need to know the color, size, etc. in order to know something is a shape. This is why I would use an abstract class to define all of the properties they have in common.
Because draw() is functionality that can apply to shapes, images, or scenes I would implement that as a Drawable
interface.
Example:
public class Square extends Shape implements Drawable{
public void draw(){
//draw code here
}
}
This way you can define all the common properties inside of Shape
and provide the functionality to draw itself through the Drawable interface.