Interface in Java | Creation and Implementation | Abstract and final methods | Java for beginner.



Interface in java
An Interface is basically a kind of class. Like classes , interface has variables and methods but with some major differences.
The differences is that interface have :-
  1. Abstract and Final Methods and
  2. Abstract and static variables.
This means Interface do not specify a code to implements methods in that.Therefore, it is the responsibility of class that implements an interface define the code for implementation of these methods.

The Syntax for defining an interface is very similar to that for defining a class. The general form is:-



interface  Interfacename 
{
variables declaration;
Methods decalaration;
}

Like Classes , Interface can also be extended. By using extends keyword that we use in class inheritance.
Let  We have declare interface name, Now make new interface name2 and extends name1.
Interface name2 extends name2
{
Body of name2;
}
Implementing Interfaces



Interface are used as “superclass” whose properties are inherited by classes. It is therefore necessary to create that inherits the given interface. This is done as follows:-


class  classname implements interfacename
{

body  of classname;
}

There are Different types of forms to implement interface:-


Example:

package Demo;

interface p1
{
   public static final String SITE_NAME1="w3schools.com";
   void displaySN1();
}
interface p2
{
   public static final String SITE_NAME2="javatpoint.com";
   void displaySN2();
}
interface p extends p1,p2
{
   public static final String SITE_NAME3="tutorialsponts.com";
   void displaySN3();
}
interface p12 extends p
{
   public static final String SITE_NAME4="guru99.com";
   void displaySN4();
}
public class Q implements p12
{
   public void displaySN1()
   {
      System.out.println("Site name is :-"+SITE_NAME1);
   }
   public void displaySN2()
   {
      System.out.println("Site name is :-"+SITE_NAME2);
  }
   public void displaySN3()
   {
      System.out.println("Site name is :-"+SITE_NAME3);
   }
   public void displaySN4()
   {
      System.out.println("Site name is :-"+SITE_NAME4);
   }
   public static void main(String[] args)
   {
      Q obj = new Q();

      System.out.println("*****Learning Website are Below Given*****\n");
      obj.displaySN1();
      obj.displaySN2();
      obj.displaySN3();
      obj.displaySN4();
   }
}


Output:-


*****Learning Website are Below Given*****

Site name is :-w3schools.com
Site name is :-javatpoint.com
Site name is :-tutorialsponts.com
Site name is :-guru99.com

Post a Comment

2 Comments