In this post, we will see what is an Interface, how to declare it and how to use polymorphically. We will also see new updates about interface in Java 8 and why Java developers have introduced method body in interface in Java 8? Moreover, What will be the use of method body in interface?
Interface
General definition: an interface refers to a common boundary or interconnection between two entities.
For instance, a keyboard in a computer system provides an interface between a human being and the computer. A natural language such as English is an interface between two humans that allows them to exchange their views.
Java definition: Interfaces are like a 100-percent abstract superclass that defines the methods a subclass must support, but not how they must be supported.
In Java, an interface is a set of abstract methods that defines a protocol (i.e., a contract for conduct). Classes that implement an interface must implement the methods specified in the interface.
An interface defines a protocol, and a class implementing the interface honors the protocol. In other words, an interface promises a certain functionality o its clients by defining an abstraction. All the classes implementing the interface provide their own implementations for the promised functionality.
In other words, an Animal interface might declare that all Animal implementation classes have an eat() method, but the Animal interface doesn't supply any logic for the eat() method. That means it's up to the classes that implement the Animal interface to define the actual code for how that particular Animal type behaves when its eat() method is invoked.
Example :
Unrelated classes can provide their own implementations when they implement Comparable. These unrelated classes have one aspect in common: they all follow the specification given by Comparable, and it is left to the implementation of these individual classes to implement compareTo() accordingly.
Conceptually, a class and an interface are two different constructs used for two different purposes. A class combines the state and the behavior of a real object, whereas an interface specifies the behavior of an abstract entity.
How to declare interface
When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it. An interface is a contract.
Interfaces can be implemented by any class, from any inheritance tree. This lets you take radically different classes and give them a common characteristic.
Think of an interface as a 100-percent abstract class. Like an abstract class,an interface defines abstract methods that take the following form:
Some point to remember about interface
How to declare interface constants(means public static final)
You're allowed to put constants(means public static final) in an interface. By doing so, you guarantee that any class implementing the interface will have access to the same constant.
By placing the constants right in the interface, any class that implements the interface has direct access to the constants, just as if the class had inherited them.
You need to remember one key rule for interface constants. They must always be
public static final
You can't change the value of a constant!(means public static final declared variable)
How Interface types can be used polymorphically
Let's say we have class Duck who can swim and quack. Whatever duck class extend this class, they have the functionality of swim and quack.
It looks like
Now suppose later, we want the fly functionality as per OO we simply add fly() method in the duck class and then all the ducks will inherit it.
By adding the fly behavior in the superclass can't not be appropriate for some Duck subclassess. For instance, RubberDuck extends Duck class.
It will become worse of WoodDuck extends Duck class as it can't fly and swim.
In this case, the use of inheritance for the purpose of reuse hasn't turned out so well when it comes to maintenance.
Now we take the fly() out of the Duck superclass and make a Flyable interface with a fly method. That way, only the ducks that are supposed to fly will implements that interface and have a fly method.
This is one of the design principle : Identify the aspects of your application that vary and separate them from what stays the same.
A reference variable can be declared as a class type or an interface type. If the variable is declared as an interface type, it can reference any object of any class that implements the interface.
Q. What will happen if class implement two interface having common method?
Ans:
That would not be a problem as both are specifying the contract that implement class has to follow.
If class C implement interface A & interface B then Class C thing I need to implement print() because of interface A then again Class think I need to implement print() again because of interface B, it sees that there is already a method called test() implemented so it's satisfied.
Most of the time we'll think why interface has no body and what if it has body what will be merits and demerits that we'll see in the next section as per draft version of Java 8.
The Interface Body in Java 8
The interface body can contain abstract methods, constants variable, 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(means public static final) declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, you can omit these modifiers.
Drawback of interface
Consider an interface that you have developed called Animal:
Suppose that, at a later time, you want to add a third method to Animal, so that the interface now becomes:
If you make this change, then all classes that implement the old Animal interface will break because they no longer implement the old interface. Programmers relying on this interface will protest loudly
Default method in interface
If you want to add additional methods to an interface, you have several options.
You could create a AnimalSwim interface that extends Animal:
Now users of your code can choose to continue to use the old interface or to upgrade to the new interface.
Alternatively, you can define your new methods as default methods. The following example defines a default method named swim:
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
Extending Interfaces That Contain Default Methods
When you extend an interface that contains a default method, you can do the following:
Q. Again one question come to mind that if two interface are providing default method with similar signatures and class is extending both the interface, will it not be again diamond problem?
Yes, you are thinking right but Java doesn't allow you to implement interface with has same default method.
Static Methods in interface
In addition to default methods, you can define static methods in interfaces
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.
This makes it easier for you to organize helper methods in your libraries; you can keep static methods specific to an interface in the same interface rather than in a separate class.
Like static methods in classes, you specify that a method definition in an interface is a static method with the static keyword at the beginning of the method signature. All method declarations in an interface, including static methods, are implicitly public, so you can omit the public modifier.
Interface in Java 9(update)
As you seen earlier, you can define abstract methods, constants variable, default methods, and static methods in java 8. Now with Java 9, you can define private methods and private static methods
Question arise, why private methods? As you can define default functionality in defaults methods that will be available to all the class who implements the interface. In static methods, we write some helper method so that it specific to interface. However, when we need to define some common functionality that is only specific to interface and no class can inherit that such as connection to logging,opening a file etc. so that it can be only used inside interface. That means no duplicate code and we can control what we want to expose to the client.
In order to write private method in interface, just use private identifier and must write the body
If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...
Interface
General definition: an interface refers to a common boundary or interconnection between two entities.
For instance, a keyboard in a computer system provides an interface between a human being and the computer. A natural language such as English is an interface between two humans that allows them to exchange their views.
Java definition: Interfaces are like a 100-percent abstract superclass that defines the methods a subclass must support, but not how they must be supported.
In Java, an interface is a set of abstract methods that defines a protocol (i.e., a contract for conduct). Classes that implement an interface must implement the methods specified in the interface.
An interface defines a protocol, and a class implementing the interface honors the protocol. In other words, an interface promises a certain functionality o its clients by defining an abstraction. All the classes implementing the interface provide their own implementations for the promised functionality.
In other words, an Animal interface might declare that all Animal implementation classes have an eat() method, but the Animal interface doesn't supply any logic for the eat() method. That means it's up to the classes that implement the Animal interface to define the actual code for how that particular Animal type behaves when its eat() method is invoked.
interface Animal{
void eat();
abstract void walk();
}
class Lion implements Animal {
@Override
public void eat() {
System.out.println("lion eating");
}
@Override
public void walk() {
System.out.println("lion running fast");
}
}
public class AnimalInterfaceDemo{
public static void main(String javalatte[]){
Lion l = new Lion();
l.walk();
l.eat();
}
}
Example :
public interface Comparable{
public int compareTo(Object o);
// Intent is to compare this object with the specified object
// The return type is integer. Returns negative,
// zero or a positive value when this object is less than,
// equal to, or greater than the specified object
}
Unrelated classes can provide their own implementations when they implement Comparable. These unrelated classes have one aspect in common: they all follow the specification given by Comparable, and it is left to the implementation of these individual classes to implement compareTo() accordingly.
Conceptually, a class and an interface are two different constructs used for two different purposes. A class combines the state and the behavior of a real object, whereas an interface specifies the behavior of an abstract entity.
How to declare interface
When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it. An interface is a contract.
Interfaces can be implemented by any class, from any inheritance tree. This lets you take radically different classes and give them a common characteristic.
Think of an interface as a 100-percent abstract class. Like an abstract class,an interface defines abstract methods that take the following form:
abstract void bounce();
But while an abstract class can define both abstract and non-abstract methods, an interface can have only abstract methods.Some point to remember about interface
- An interface cannot be instantiated.
- All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract.
public abstract interface Rollable { }
public interface Rollable { }
Both of these declarations are legal, and functionally identical. - All variables defined in an interface must be public, static, and final—in other words, interfaces can declare only constants (means public static final) , not instance variables.
- Interface methods must not be static.
- Because interface methods are abstract, they cannot be marked final, strictfp, or native
- An interface can extend one or more other interfaces.
- An interface cannot extend anything but another interface.
- An interface cannot implement another interface or class.
- An interface must be declared with the keyword interface.
- Interface types can be used polymorphically
- An interface can be declared within another interface or class; such interfaces are known as nested interfaces.
You must remember that all interface methods are public and abstract regardless of what you see in the interface definition.
How to declare interface constants(means public static final)
You're allowed to put constants(means public static final) in an interface. By doing so, you guarantee that any class implementing the interface will have access to the same constant.
By placing the constants right in the interface, any class that implements the interface has direct access to the constants, just as if the class had inherited them.
You need to remember one key rule for interface constants. They must always be
public static final
interface constants{
int MAX = 10;
public static final int MIN = 2;
}
public class InterfaceConstant implements constants{
public static void main(String javalatte[]){
System.out.println("MIN = "+MIN+" MAX = "+MAX);
}
}
You can't change the value of a constant!(means public static final declared variable)
How Interface types can be used polymorphically
Let's say we have class Duck who can swim and quack. Whatever duck class extend this class, they have the functionality of swim and quack.
It looks like
class Duck{
public void swim(){
System.out.println("I'm swiming");
}
public void quack(){
System.out.println("quacking......");
}
}
class MallardDuck extends Duck{
// it has both functionality of swim and qauck
}
class RedHeadDuck extends Duck{
// it has both functionality of swim and qauck
}
Now suppose later, we want the fly functionality as per OO we simply add fly() method in the duck class and then all the ducks will inherit it.
class Duck{
public void swim(){
System.out.println("I'm swiming");
}
public void quack(){
System.out.println("quacking......");
}
public void fly(){
System.out.println("flying.....");
}
}
By adding the fly behavior in the superclass can't not be appropriate for some Duck subclassess. For instance, RubberDuck extends Duck class.
class RubberDuck extends Duck{
public void quack(){
System.out.println("squeak......");
}
//It can't fly
}
It will become worse of WoodDuck extends Duck class as it can't fly and swim.
In this case, the use of inheritance for the purpose of reuse hasn't turned out so well when it comes to maintenance.
Now we take the fly() out of the Duck superclass and make a Flyable interface with a fly method. That way, only the ducks that are supposed to fly will implements that interface and have a fly method.
This is one of the design principle : Identify the aspects of your application that vary and separate them from what stays the same.
A reference variable can be declared as a class type or an interface type. If the variable is declared as an interface type, it can reference any object of any class that implements the interface.
class Duck{
public void swim(){
System.out.println("I'm swiming");
}
public void quack(){
System.out.println("quacking......");
}
}
interface Flyable {
void fly();
}
class RubberDuck extends Duck{
public void quack(){
System.out.println("squeak......");
}
}
class MallardDuck extends Duck implements Flyable{
@Override
public void fly() {
System.out.println("MallardDuck flying");
}
}
class RedHeadDuck extends Duck implements Flyable{
@Override
public void fly() {
System.out.println("RedHeadDuck flying");
}
}
public class PolymorphicallyInterfaceDemo {
public static void main(String javalattep[]){
Flyable f = new RedHeadDuck();
f.fly();
f = new MallardDuck();
f.fly();
RedHeadDuck r = new RedHeadDuck();
r.fly();
}
}
Q. What will happen if class implement two interface having common method?
Ans:
That would not be a problem as both are specifying the contract that implement class has to follow.
If class C implement interface A & interface B then Class C thing I need to implement print() because of interface A then again Class think I need to implement print() again because of interface B, it sees that there is already a method called test() implemented so it's satisfied.
interface A{
void print();
}
interface B{
void print();
}
class C implements A,B{
@Override
public void print() {
System.out.println("java-latte.blogspot.in");
}
}
public class TwoInterfaceDemo {
public static void main(String javalatte[]){
C c = new C();
c.print();
}
}
Most of the time we'll think why interface has no body and what if it has body what will be merits and demerits that we'll see in the next section as per draft version of Java 8.
The Interface Body in Java 8
The interface body can contain abstract methods, constants variable, 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(means public static final) declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, you can omit these modifiers.
Drawback of interface
Consider an interface that you have developed called Animal:
public interface Animal {
void eat();
int weight(String s);
}
Suppose that, at a later time, you want to add a third method to Animal, so that the interface now becomes:
public interface Animal {
void eat();
int weight(String s);
void swim();
}
If you make this change, then all classes that implement the old Animal interface will break because they no longer implement the old interface. Programmers relying on this interface will protest loudly
Default method in interface
If you want to add additional methods to an interface, you have several options.
You could create a AnimalSwim interface that extends Animal:
public interface AnimalSwim extends Animal {
boolean swim();
}
Now users of your code can choose to continue to use the old interface or to upgrade to the new interface.
Alternatively, you can define your new methods as default methods. The following example defines a default method named swim:
public interface Animal {
void eat();
int weight(String s);
default void swim() {
// Method body
}
}
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
- You specify that a method definition in an interface is a default method with the default keyword at the beginning of the method signature.
- All method declarations in an interface, including default methods, are implicitly public, so you can omit the public modifier.
Extending Interfaces That Contain Default Methods
When you extend an interface that contains a default method, you can do the following:
- Don't mention the default method,and lets your extend interface inherit the default method.
- You can redeclare the default method which make them abstract again. Similary, when abstract class extend abstract class.
- You can redefine the default method similar to overriding.
Q. Again one question come to mind that if two interface are providing default method with similar signatures and class is extending both the interface, will it not be again diamond problem?
Yes, you are thinking right but Java doesn't allow you to implement interface with has same default method.
Static Methods in interface
In addition to default methods, you can define static methods in interfaces
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.
This makes it easier for you to organize helper methods in your libraries; you can keep static methods specific to an interface in the same interface rather than in a separate class.
interface stack{
void push(int i);
int pop();
int peek();
static calculateElement(StackImp st){
// code to calculate the no of element in stack
}
}
Like static methods in classes, you specify that a method definition in an interface is a static method with the static keyword at the beginning of the method signature. All method declarations in an interface, including static methods, are implicitly public, so you can omit the public modifier.
Interface in Java 9(update)
As you seen earlier, you can define abstract methods, constants variable, default methods, and static methods in java 8. Now with Java 9, you can define private methods and private static methods
Question arise, why private methods? As you can define default functionality in defaults methods that will be available to all the class who implements the interface. In static methods, we write some helper method so that it specific to interface. However, when we need to define some common functionality that is only specific to interface and no class can inherit that such as connection to logging,opening a file etc. so that it can be only used inside interface. That means no duplicate code and we can control what we want to expose to the client.
In order to write private method in interface, just use private identifier and must write the body
If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...
The best explanation on interface concept in java
ReplyDeletehttps://www.codingame.com/profile/f18c9450b05272b794be9e9286efe2d49705934
ReplyDeletehttps://www.openlearning.com/u/namazquran-quyfif/
https://slides.com/namaz123
https://yoomark.com/content/namaz-quran
https://www.ted.com/profiles/28744932
https://archive.org/details/@namaz123
https://www.imdb.com/user/ur133844307/?ref_=nv_usr_prof_2
https://www.prestashop.com/forums/profile/1680732-namaz123/?tab=field_core_pfield_19