Differences:
Similarities:
- Similar to abstract classes, we can not create objects of interfaces, but they can be used as references. Any object of the class implementing that interface can be assigned to that reference. See
LINE A
and LINE D
below.
- Every class implementing an interface has 'IS-A' relation with interface, so where ever we can use the interface, we can also use the class which implements it.
- Similar to abstract classes, the abstract methods can be called using
the interface references. See
LINE B
below.
- As with classes extending abstract class, any class implementing an interface should implement all the methods of the interface. If it is not implementing all the methods, then that class should be marked as
abstract
.
interface IA
{
void printA();
}
class A implements IA
{
public void printA()
{
System.out.println("A's implementation of printA method.");
}
}
...
IA ia = new A(); // Valid - LINE A
ia.printA(); // Valid - LINE B
A a1 = new A();
ia = a1; // Valid - LINE D
IA ia2 = new IA(); // INVALID
...
See
Creating Interface In Java With Example Program to for more details about interfaces and their rules.