Interfaces belong to abstract class in Java which prevents it from instantiating. If an interface is instantiated, it will rebel the model of Object Oriented Programming because some methods present in an interface does not have any definitions. Instantiating an interface will result in compile error.
Interfaces does not have any variables or method bodies. When an object was created some methods will be called to use the variables on that particular object. If no method bodies are present in that object, Java will throw an linking error. Before to begin, just read out How to Interface Anonymous Inner Class?
Let us consider an interface named Boo is declared:
public interface Boo
{
Int club();
}
Consider the following as a valid code.
Boo boo = new Boo();
int a= boo.club();
In the above code, the value of integer “a” is not mentioned anywhere in the program. Implementation of club() is also not mentioned anywhere in the program. It is will be worthless to call without implementation of ‘a’ and club() which will result in errors.
Interface is like a contract which should be respected by class. If a developer define an interface and abstract class, it is impossible to all classes to accept that definition. Consider class as a blueprint of a house, it is easy to instantiate(create) the whole plan. Interface and abstract classes are like floor plan of a particular room. One cannot instantiate a particular room without altering the whole plan.
To explain articulately, the process of instantiating an interface is like breaking the door to get inside instead of opening it.
- Many: Java interview Q&A available here
Consider the following code for example
public interface Matrix
{
/* Your source code should be here…*/
}
public class Myo implements M1
{
public void T1(M1 a )
{
/* Complete code details here */
}
}
In the above code the method Trinity will accept argument from the type Matrix. A class which implements Matrix interface will be passed as an argument. Interface is a type, a developer will be permitted to write the code within the parameter of that particular type.
Both interfaces and abstract classes contain concrete or abstract methods. Instantiation of interfaces cannot be done directly. In direct process of creating instance by calling constructors is also not possible. If an instance is created by extending the interface class, the compiler will initialize both the classes.