☰
In OOP, Objects interact with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your mobile phone, for example, are the interface between you and the electronic circuit on the other side of its plastic casing. You press the "call" button to connect to your loved ones.
An interface is a programming structure that enforce certain properties on an object (class). For example, say we have a car class and a scooter class and a truck class. Each of these three classes should have a start_engine() action. How the "engine is started" for each vehicle is left to each particular class, but the fact that they must have a start_engine action is the domain of the interface.
In its most common form, an interface is a group of related methods with empty bodies.A car's behavior, if specified as an interfacce, might appear as follows:
public interface Car {
void startEngine();
void accelerate();
void applyBrakes();
}
Note that the method signatures have no braces and are terminated with a semicolon.A class implementing this interface looks like this:
public class BMW implements Car {
//The compiler will now require that methods
//startEngine, accelerate, applyBrakes
//all be implemented. Compilation will fail if those
//methods are missing from this class.
public void startEngine() {
}
public void accelerate() {
}
public void applyBrakes() {
}
}
Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
An interface declaration consists of modifiers, the keyword interface, the interface name, a comma-separated list of parent interfaces (if any), and the interface body. For example:
public interface Car extends vehicle1, vehicle2 {
void startEngine();
void accelerate();
void applyBrakes();
}
The public access specifier indicates that the interface can be used by any class in any package.An interface can extend other interfaces, just as a class.However, whereas a class can extend only one other class, an interface can extend any number of interfaces.
The interface body can contain abstract methods, default methods, and static methods. An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation). Default methods are defined with the default modifier, and static methods with the static keyword. All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.
In addition, an interface can contain constant declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, you can omit these modifiers.
To get the best out of interface, you have to implement interface to class.To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
A class that implements an interface must implement all the methods declared in the interface. The methods must have the exact same signature as declared in the interface. The class need not implement the variables of an interface.
public interface Car {
void startEngine();
void accelerate();
void applyBrakes();
}
public class BMW implements Car {
public void startEngine() {
}
public void accelerate() {
}
public void applyBrakes() {
}
}
Yes, class can implement multiple interface unlike base classes.In this case, class have to implement all the methods declared in all the interfaces implemented.
public interface Car {
void startEngine();
void accelerate();
void applyBrakes();
}
public interface ManualCar {
void changeGear();
}
public class BMW implements Car, ManualCar{
public void startEngine() {
}
public void accelerate() {
}
public void applyBrakes() {
}
public void changeGear() {
}
}
Class BMW implements 2 interfaces called Car and ManualCar and implements all the methods declared in Car and ManualCar interfaces.
you will have to import the interface if the interfaces are not located in the same packages as the implementing class. Interfaces are imported just like classes.
Interface declared within an interface or class is known as Nested Interface. Nested interface cannot be accessed directly, they must be referred by the outer interface or class
interface interface_A{
//some code
interface nested_interface_B{
//some code
}
}
Just like classes can inherit, interface too can inherit from other interfaces.
public interface ParentInterface {
public void display();
}
public interface ChildInterface extends ParentInterface {
public void doWrok();
}
Now any class implementing ChildInterface has to implement all methods declared in ChildInterface as well as ParentInterface.
public class Demo implements ChildInterface {
public void display()
{
//some code
}
public void doWrok()
{
//some code
}
}
But unlike classes, interfaces can inherit from multiple interfaces. You can specify that by listing all interfaces to inherit from, separated by comma. A class implementing an interface which inherits from multiple interfaces must implement all methods from the interface and its parent interfaces.
public interface GrandParentInterface {
public void getInfo();
}
public interface ParentInterface {
public void display();
}
public interface ChildInterface extends ParentInterface, GrandParentInterface {
public void doWrok();
}
[Note]:When implementing multiple interfaces, certainly there are no rules for how you handle the case when multiple interfaces have methods with the same signature that is same name and parameters.
Interfaces provide a way to achieve polumorphism in Java. Here polymorphism means an object can be used as if it were of different types.
interface Vehicle {
void applyBrakes();
}
class Car implements Vehicle {
public void applyBrakes() {
System.out.println("Car applied brakes");
}
}
class Bike implements Vehicle {
public void applyBrakes() {
System.out.println("Bike applied brakes");
}
}
class Demo {
public void Test() {
Vehicle vehicle1 = new Car();
Vehicle vehicle2 = new Bike();
vehicle1.applyBrakes();
vehicle2.applyBrakes();
}
}
Output:
Car applied brakes
Bike applied brakes
Still not convinced? Lets change the code of Demo class a bit so that it becomes evident.
class Demo {
public void Test() {
List<Vehicle> list = new ArrayList<Vehicle>(); //this is also way of polymorphism
list.add(new Car());
list.add(new Bike());
for(Vehicle myVehicle:list)
{
myVehicle.applyBrakes();
}
}
}
Output:
Car applied brakes
Bike applied brakes
Now you see, the code looks so much cleaner, thats polymorphism for you.
A interface with no field nor methods is called as Marker interface or Tag interface. in Java some examples of tag interfaces are: Serializable, Clonnable, EventListener etc.
You will be thinking, why define an interface with no methods? Since no methods marker interface can never define behavior. But marker interface caries type information which can be used to solve some problem.
Marker interface are used to indicate or signal something to compiler or JVM. For example, Serializable. If JVM sees a any class with Serializable interface, it does some special operation on it.
By answering like this, interviewer may ask "Why this indication or signalling cannot be done in other ways?". Answer is YES can be done by using some flags inside a class or much better option for Java 1.5 onwards is annotations.
public interface Serializable{
}
[Note]:A marker annotation can serve the same purpose as a marker Interface, that is to 'mark' a class for something. But, if you use a marker interface then you have the benefit of compile time type checking. But annotations have lot many other benefits than marker interface.
Conclusion: marker interface in Java is used to indicate something to compiler, JVM but Annotation does better job.
Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit characteristics and features from more than one parent object or parent class. Unlike some other popular object oriented programming languages like C++, java doesn't provide support for multiple inheritance in classes. Java doesn't support multiple inheritance in classes because it can lead to diamond problem as discuessed in previous chapter and rather than providing some complex way to solve it, there are better ways through which we can achieve the same result as multiple inheritance, that is using interfaces.
interface A
{
public void myMethod();
}
interface B
{
public void myMethod();
}
class C implements A, B
{
public void myMethod()
{
System.out.println(" Multiple inheritance using interfaces");
}
}
In the above code, class 'C' implemented two interfaces 'A' and 'B'. A class can implement mulitple interfaces. In the above case there is no ambiguity even though both the interfaces are having same method. That is because methods in an interface are always abstract by default, which are meant to be implemented in concrete implemented class.
Difference between classes and interfaces is that classes can have fields whereas interfaces cannot.In addition, you can instantiate a class to create an object, which you cannot do with interfaces.An object stores its state in fields, which are defined in classes.Now if you inherit or extend more than one class and you create an object of that class, that object will inherit fields from all of the class's superclasses.What if methods or constructors from different superclasses instantiate the same field? Which method or constructor will take precedence? That is why multiple inheritance through classes is not permitted. Because interfaces do not contain fields, you do not have to worry about problems that result from multiple inheritance of state.
If you start to write a simple program, you may not think about the need of using an Interface. But when you are building a larger system which keeps evolving, it is a good idea to use Interface. One of the advantage of Interface in Java is it allows multiple inheritance.It allows you to write flexible code, which can adapt to handle future requirements.
Interfaces are a way to declare a contract for implementing classes to fulfil. Interface's main goal is to create abstraction and decoupled designs between consumers and producers.
What would you like to have, hundreds of abstract methods in one single Abstract Class or make as many interfaces for specific interrelated abstract methods and only use those which you want by implementing as many interface needed ? Yes definetly you should go for interface, as it provides lot of flexibility.
abstract class A
{
//hundreds of abstract methods();
abstract methodA();
abstract methodB();
abstract methodC();
}
//OR
interface ForMethodAOnly
{
void methodA();
}
interface ForMethodBandmethodCOnly
{
void methodB();
void methodC();
}
Use only those methods which are required by implementing respective interface.If you are inheriting abstract class then you have to implement many unnecessary methods, which is not a good programming practice.
"Programming to interface than implementation" is one of the popular Object oriented design principle, and use of interface promotes this. A code written on interface is much more flexible than the one which is written on implementation.
So you can say an interface is fully utilized when dependency injection techniques is used to inject required implementation on run time.Using references to interfaces instead of their concrete implementation classes helps in minimizing ripple effects, as the consumer of an interface reference doesn't have to worry about the changes in the underlying concrete implementation.
Use of interface allows you to supply a new implementation, which could be more robust, better performance in later stage of your development.
For example, XYZ comapany creates an API(Application Programming Interfaces) for converting to pdf.It writes various classes to provide the converting to pdf functionalities. So, their approach will be to create interfaces, and make classes implementing them. In this way the when the software package is delivered to clients , clients can invoke the methods by looking at the method signatures declared inside the interfaces.They won't see the actual implementation of the methods. As a result the implementation part will be a secret. Later on the company may decide to re-implement the methods in another way. But the clients are concerned about the interfaces only which is why their code wont be effected. This is the advantage of interfaces.
The choice of whether to design your functionality as an interface or an abstract class can sometimes be a difficult one.
Lets look at an example which would cover above points.
abstract class Car{
public void accelerate() {
//do something to accelerate
}
public void applyBrakes() {
//do something to apply brakes
}
public abstract void changeGears();
}
Now, any Car that wants to be instantiated must implement the changeGears method.
class BMW extends Car{
public void changeGears(){
System.out.println("Automatic gear shift");
}
}
class Ford extends Car{
public void changeGears(){
System.out.println("6-speed manual gear shift");
}
}
Now you could ask why abstract class, why not interface and ask BMW and Ford to implement that interface.Sure you can do that but you would also need to implement accelerate and applyBrakes methods in all the sub classes.By abstract classes, you can inherit the implementations of non-abstract methods, which you can't do that with interfaces.
consider the following example in favor of interfaces.Lets say you have an interface for a Director and for an actor.
public interface Actor{
void perform();
}
public interface Producer{
void invest();
}
Nowadays most of the actors are rich enough to produce their own movie. If we are using interfaces rather than abstract classes, we can implement both Actor and Producer. Also we could define a new ActorProducer interface that extends both.
public interface ActorProducer extends Actor, Producer{
...
}
Yes we could achieve the same using abstract classed, but for abstract classes would require massive hierarchical type framework.
I use base abstract classes to describe what an object is and use interface to describe capabilities of an object.
BMW is a Car and automatic gear shift is its capabilities.
In programming world, classes are nouns(like BMW, Ford) and interfaces are adjectives(automatic transmission, power steering). And Yes you can use both together to get the best out of both. The only drawback of doing that is calling methods via their interface name is slightly slower than calling them via their abstract class name as it requires extra indirection.