An interface is a static context template that classes can implement. The methods within the interface have no body and must be of public access.
In addition, interfaces can also contain "constants" in which data is declared and defined.
An example--
public interface MyInterface{
public final int VALUE = 100; // constant
public void doSomething(); // method declaration within interface
}
--when a class implements an interface, the class also implements the methods the interface contains. However, the implementing class MUST define the methods implemented.
An example--
public class MyTestClass implements MyInterface{
public void doSomething(){
System.out.println(VALUE);
}
}
--notice that the class MyTestClass doesn't declare VALUE however it is defined in the interface and therefore MyTestClass implements the public-accessible VALUE also.
An Abstract class is much like both a class AND an interface, however moreso a class.
An Abstract class has the potential to have default methods and interface-like methods where the methods MUST be defined by concrete subclasses that extend from the abstract class.
Furthermore, the concept of Abstract is "not fully defined" so in that respect, abstract classes cannot be instantiated.
An example--
public abstract class MyAbstractClass{
protected abstract void subCommand();
public final void templateMethod(){
System.out.println("Performing a defined command...");
subCommand();
System.out.println("SubCommand finished!");
}
}
--do not be distracted by the protected and final modifiers. The key focus is the abstract void subCommand method. Notice that an abstract class is like an interface in which it can house methods without definitions (so long as they are declared abstract) and additionally you can't instantiate an abstract class much like you can't instantiate an interface.
However when you are using an abstract class in a subclass you must override the abstract methods you are implementing from the abstract class.
An example--
public class MyOtherClass extends MyAbstractClass{
protected void subCommand(){
System.out.println("Whoo! This is my method! O_O");
}
public static void main(String... args){
MyAbstractClass mac = new MyOtherClass();
mac.templateMethod();
}
}
--notice that I'm storing MyOtherClass into a reference-variable called MyAbstractClass and then the templateMethod is called. Because MyOtherClass has a specialized implementation of subCommand, the call to templateMethod polymorphically calls the overridden subCommand within the template algorithm.
Hopefully with the above example, you can see why abstract classes and interfaces are extremely useful.
The major difference between an abstract class and an interface is the way Java handles each -
you can extend only one class but you can implement an infinite amount of interfaces.
That being said, use interfaces whenever possible if the implementing class needs more implementations.