Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Recently I have started to wrap my head around OOP, and I am now to the point where the more I read about the differences between abstract classes and interfaces the more confused I become. So far, neither can be instantiated. interfaces are more or less structural blueprints that determine the skeleton and abstracts are different by being able to partially develop code.

I would like to learn more about these through my specific situation. Here is a link to my first question if you would like a little more background information: What is a good design model for my new class?

Here are two classes I created:

class Ad {
    $title;
    $description
    $price;

    function get_data($website){  }

    function validate_price(){  }
 }


class calendar_event {
    $title;
    $description

    $start_date;

    function get_data($website){ //guts }

    function validate_dates(){ //guts }
 }

So, as you can see these classes are almost identical. Not shown here, but there are other functions, like get_zip(), save_to_database() that are common across my classes. I have also added other classes Cars and Pets which have all the common methods and of course properties specific to those objects (mileage, weight, for example).

Now I have violated the DRY principle and I am managing and changing the same code across multiple files. I intend on having more classes like boats, horses, or whatever.

So is this where I would use an interface or abstract class? From what I understand about abstract classes I would use a super class as a template with all of the common elements built into the abstract class, and then add only the items specifically needed in future classes. For example:

abstract class content {
    $title;
    $description


    function get_data($website){  }

    function common_function2() { }
    function common_function3() { }
 }


class calendar_event extends content {

    $start_date;

    function validate_dates(){  }
 }

Or would I use an interface and, because these are so similar, create a structure that each of the subclasses are forced to use for integrity reasons, and leave it up to the end developer who fleshes out that class to be responsible for each of the details of even the common functions. my thinking there is that some 'common' functions may need to be tweaked in the future for the needs of their specific class.

Despite all that above, if you believe I am misunderstanding the what and why of abstracts and interfaces altogether, by all means let a valid answer to be stop thinking in this direction and suggest the proper way to move forward!

Thanks!

share|improve this question
    
There are lot of good examples online. I think this is one among them. javapapers.com/core-java/abstract-and-interface-core-java-2/… –  Siva Nov 4 '12 at 0:25
add comment

6 Answers 6

up vote 15 down vote accepted

In layman's terms:

Interfaces are for "can do/can be treated as" type of relationships.

Abstract ( as well as concrete ) classes are for "is a" kind of relationship.

Look at these examples:

class Bird extends Animal implements Flight;
class Plane extends Vehicle implements Flight, AccountableAsset;
class Mosquito extends Animal implements Flight;
class Horse extends Animal;
class RaceHorse extends Horse implements AccountableAsset;
class Pegasus extends Horse implements Flight;

Bird, Mosquito and Horse are Animals. They are related. They inherit common methods from Animal like eat(), metabolize() and reproduce(). Maybe they override these methods, adding a little extra to them, but they take advantage of the default behavior implemented in Animal like metabolizeGlucose().

Plane is not related to Bird, Mosquito or Horse.

Flight is implemented by dissimilar, unrelated classes, like Bird and Plane.

AccountableAsset is also implemented by dissimilar, unrelated classes, like Plane and RaceHorse.

Horse doesn't implement Flight.

As you can see classes (abstract or concrete) helps you build a hierarchies, letting you inhering code from the upper levels to the lower levels of the hierarchy. In theory the lower you are in the hierarchy, the more specialized your behavior is, but you don't have to worry about a lot of things that are already taken cared of.

Interfaces, in the other hand create no hierarchy, but they can help homogenize certain behaviors across hierarchies so you can abstract them from the hierarchy in certain contexts.

For example you can have a program sum the value of a group of AccountableAssets regardless of their being RaceHorses or Planes.

share|improve this answer
    
@robert-harvey Thanks for the edit ! –  user61852 Nov 6 '12 at 19:37
add comment

You could deduce the answer logically since you seem to be aware of the differences between the two.

Interfaces define a common contract. Such as an interface called IAnimal, where all animals share functions such as Eat(), Move(), Attack() etc. While all of them share the same functions, all or most of them have a different way (implementation) of achieving it.

Abstract classes define a common implementation and optionally common contracts. For example a simple Calculator could qualify as an abstract class which implements all the basic logical and bitwise operators and then gets extended by ScientificCalculator, GraphicalCalculator and so on.

If you have common implementation then by all means, encapsulate the functionality in an abstract class to extend from. I have near 0 PHP experience, but i don't think you can create interfaces with non constant fields. If the fields are common between your instance classes then you are forced to use an Abstract class, unless you define access to them via getters and setters.

Also, there seems to be no shortage of results in Google.

share|improve this answer
2  
+1 for the realistic examples. –  Brian Wigginton Nov 4 '12 at 5:45
add comment

Long story short. Abstract classes are much like Interfaces in that they both provide a template of what methods should be within the inheriting class, but there are big differences: - Interfaces only define names/types of methods that need to exist in an inheriting class, while abs-classes can have complete default code of method and just the details may need to be over-ridden. - Interfaces cannot have access modifiers. - Interfaces cannot have fields. - Classes cannot have multiple inheritance of classes, while they can inherit multiple interfaces. - Also, classes provide a hierarchy structure so that only classes derived from a specific class need to follow the guidelines of the abstract class: object->specific object-> very specific object. Interfaces on the other hand can be inherited by anybody anywhere.

In my opinion abstract classes are more common in that they can provide default implementation of code right away, but in large scale projects where you need to standardize certain classes, interfaces could come in handy.

Hope that helps, but there is lots of info on this online, Leo

share|improve this answer
1  
Classes cannot have multiple inheritance -- True for languages like Java and C#, not true for C++. –  Robert Harvey Nov 4 '12 at 5:55
add comment

First off, you should understand that you will often provide both an interface and an abstract class. The reason for this, and the core difference between the two, is that they allow you to re-use different code, and so solve different problems.

Interfaces allow you to re-use client code with different implementations. A client of you get_data($website) class doesn't care about the $title or $description items. It just wants to instruct your content to load the data. If you have different types of content, some of which need a $description, and some which do not, you could provide a ContentInterface class that only specifies the signature of your child classes. Now the client can have any number of different Contents without every knowing exactly how they work. The Liskov Substitution Principle is a good thing to read about to study this idea. I also like Uncle Bob's writing on the topic. Interfaces are very important to unit testing, and creating interfaces is a good habit to learn.

Abstract classes allow you to re-use common implementation details across a set of classes that share a common ancestor. In your question you seem to have a good handle on why you would inherit implementation from an abstract class. It is still dangerous to depend on the internals of a base class - it is very easy to violate encapsulation and create children who depend on specific implementation details of a base class. The Template Method Pattern provides a common and healthy example of how to use base classes without violating encapsulation.

So, as I hope I've shown, you will often provide interfaces for the clients of your class hierarchy, so you can safely change your implementation without impacting the client code. This allows the client to write unit tests using Mock Objects that inherit your interface. And you will also provide abstract classes that allow re-use of common logic or enforce semantics for the child classes.

share|improve this answer
add comment

Difference is subtle but a clear one. Interface is about polymorphic behavior. Abstract class is about reuse and polymorphic behavior.

If you want to put emphasis on reuse and polymorphic behavior, choose abstract class. For example, different types employees have different provisions but all receive a few common. So, abstract class is suitable to represent it because commonalities can be expressed in a base abstract class Employee and the difference can be implemented in derived classes like Manager or Worker etc.

If you want to put emphasis on only polymorphic behavior, choose interface. Interface is more about contract, i.e., an object or hierarchy saying it conforms to certain behavior. For example, all employees have leave provision but different types of employees have different types of provisionss. So, each different type of employee requires a different leave calculator. Here interface is a good choice because all types of employees can implement a LeaveCalculator interface with a Calculate() behavior differently.

share|improve this answer
add comment
  1. Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implement a default behavior.
  2. Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
  3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc.
  4. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
  5. An interface can extend another Java interface only an abstract class can extend another Java class and implement multiple Java interfaces.
  6. A Java class can implement multiple interfaces but it can extend only one abstract class.
  7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
  8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
  9. Interface and abstract class in Java is that you cannot create non abstract method in interface, every method in interface is by default abstract, but you can create non abstract method in abstract class.
  10. Abstract class vs. interface in Java is that, interfaces are better suited for Type declaration and abstract class is more suited for code reuse and evolution perspective.
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.