What
is an interface?
Interface looks like class but it is not a class. An interface
can have methods and variables just like the class but the methods declared in
interface are by default abstract (only method signature, no body). Also, the
variables declared in an interface are public, static & final by default.
What
is the use of interfaces?
As mentioned above they are used for abstraction. Since methods
in interfaces do not have body, they have to be implemented by the class before
you can access them. The class that implements interface must implement all the
methods of that interface. Also, java programming language does not support
multiple inheritance, using interfaces we can achieve this as a class can
implement more than one interfaces, however it cannot extend more than one
classes.
Benefits of having interfaces:
Following are the advantages of using interfaces:
Without bothering about the implementation part, we can achieve
the security of implementation
In java, multiple inheritance is not
allowed, However by using interfaces you can achieve the same . A class can
extend only one class but can implement any number of interfaces. It saves you
from Deadly Diamond of Death(DDD) problem.
Syntax
interface MyInterface
{
public void method1();
public void method2();
}
Note:
All
the methods are public abstract by default
These
methods are not having body
Example
Interface Implementation
This is how a class implements an
interface. It has to provide the body of all the methods that are declared in
interface.
Note: class implements interface but an interface extends another interface.
Note: class implements interface but an interface extends another interface.
package com.opps;
public interface Customer {
public void saveCustomer();
public void displayCustomer();
public void editCustomer();
public void deleteCustomer();
}
package com.opps;
public class CustomerImpl implements Customer{
public void saveCustomer() {
System.out.println("Save the Customer Details");
}
public void displayCustomer() {
System.out.println("Display the Customer Details");
}
public void editCustomer() {
System.out.println("Edit the Customer Details");
}
public void deleteCustomer() {
System.out.println("Delete the Customer Details");
}
}
package com.opps;
public class CustomerTest {
public static void main(String[] args)
{
Customer
customer=new
CustomerImpl();
customer.saveCustomer();
customer.displayCustomer();
customer.editCustomer();
customer.deleteCustomer();
}
}
output:
Save the Customer Details
Display the Customer Details
Edit the Customer Details
Delete the Customer Details
Save the Customer Details
Display the Customer Details
Edit the Customer Details
Delete the Customer Details
No comments:
Post a Comment