What is an interface? Explain with an example using java

What is an interface? Explain with an example using java.

A class that implements an interface is compelled to implement all the methods that have been declared in the interface.

For a class to successfully compile, it should have implemented all the methods in the interface. This way, the interface makes the behavior of the class formal by defining its behaviour.

Syntax:
interface INTERFACE_NAME
{
   return_type method1_name();
   return_type method2_name();
}

class CLASS_NAME implements INTERFACE_NAME
{
   return_type method1_name()
   {
       //implementation method1
       //implementation method2
   }
}

Advantages and disadvantages of interfaces.

Advantages

- Interfaces are mainly used to provide polymorphic behavior.
- Interfaces function to break up the complex designs and clear the dependencies between objects.

Disadvantages

- Java interfaces are slower and more limited than other ones.
- Interface should be used multiple number of times else there is hardly any use of having them.
How can we implement multiple inheritances in java?
Multiple inheritances - Java does not support multiple inheritances. However, interfaces can be used in place of multiple inheritances...
Purpose of ‘instanceof’ keyword in java
Purpose of ‘instanceof’ keyword - The instanceof keyword is used to check the type of an instance of an object...
What is cloning? Explain how to design a class that supports cloning
What is cloning? - If you create an object on the heap and assign the object to another object, then the compiler does not create another object...
Post your comment