Sei sulla pagina 1di 2

Implements and Extends:

In Java, Classes implement Interfaces. Interfaces are contracts. In other words, interfaces
specify the APIs (Application Programming Interfaces) that will be used by other
applications/modules. Interfaces make 'abstraction', one of the key object oriented principles
possible. Hence all the methods in interfaces are abstract without concrete definitions. So some
concrete 'Class' has to 'implement' an interface and provide definitions for the APIs. When a
class 'implements' an interface it defines the APIs declared by the interface.
Example:
//Interface Pizza exposes the APIs makeDough, addSauce and setCrust.
public interface Pizza
{
void makeDough();
void addSauce();
void setCrust();
}
//CheesePizza implements Pizza and defines the APIs
class CheesePizza implements Pizza
{
String dough, sauce, crust;
void makeDough()
{
dough = "soft";
}
void addSauce()
{
sauce = "tomato";
}
void setCrust()
{
crust = "thin";
}
}
When a class 'extends', it usually extends another class. 'extends' signify inheritance. For
example, a Dog class can extend an Animal class and inherit all animal properties and behaviors.
In addition to the animal characteristics, it can extend and add its own specific properties and
behaviors. It can also override some characteristics of an animal.
//Base class Animal
class Animal
{
void hello()

{
System.out.println("Hello I am an animal");
}
}
//Dog extends Animal and inherits its characteristics
class Dog extends Animal
{
void hello()
{
System.out.println("Hello I am a dog");
}
void bark()
{
System.out.println("bark");
}
}
Also note that an interface can extend multiple interfaces. But a class can extend only one class.
A class can also implement multiple interfaces!.
Although, Implements and Extends are two keywords that provide a mechanism to inherit
attributes and behavior to a class in Java programming language, they are used for two different
purposes. Implements keyword is used for a class to implement a certain interface, while Extends
keyword is used for a subclass to extend from a super class. When a class implements an
interface, that class needs to implement all the methods defined in the interface, but when a
subclass extends a super class, it may or may not override the methods included in the parent
class. Finally, another key difference between Implements and Extends is that, a class can
implement multiple interfaces but it can only extend from one super class in Java. In general,
usage of Implements (interfaces) is considered more favorable compared to the usage of Extends
(inheritance), for several reasons like higher flexibility and the ability to minimize coupling.
Therefore in practice, programming to an interface is preferred over extending from base classes.