Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

100% Abstract class vs Interface

Tags:

java

oop

php

Is there a reason to use a 100% abstract class and not an interface ? Can you give me a good example when to use both so I can grasp the concept a little?

Update: 100% Abstract class -> abstract class with only abstract methods. I'm curios if there are differences between php and java regarding this aspect.

Update2: Even if I understand most of the reasons I'm more interested in the conceptual more than technical reasons.

like image 863
johnlemon Avatar asked Sep 28 '10 07:09

johnlemon


2 Answers

If by "100% abstract class" you mean "abstract class with no concrete methods", then I can think of a reason: visibility.

You can define an abstract method to be protected, and hence not part of the public API of the class. However, that seems like an odd design.

Another thing that came to my mind is when you expect to add common functionality to the base class - i.e. if it is likely to have some utility methods shared by all implementors, but these methods are not implemented.

Another thing - instance variables. You can have inheritable instance variables in the abstract class.

like image 168
Bozho Avatar answered Sep 16 '22 22:09

Bozho


The one case where an "100% abstract class" may be advantageous over an interface is in places where API stability is a key concern.

If you write an API where other people are expected to implement your interface you have to stick to the interface. You can't add any methods to the interface later on because that would break all clients (you would have to work around this by implement a second interface and let your code check againt the usage with instanceof checks and provide an fallback).

If you realize the same with an class you can add (non abstract) methods later on without breaking the client.

like image 32
Arne Deutsch Avatar answered Sep 17 '22 22:09

Arne Deutsch