All about Interface in java

Interface

Interface in javaA special type of class, which is used to declare only abstract methods is called as interface.

Keyword "interface" is used to define this class.

Keyword "implemets" is used to inherit the interface into classes.

interface xyz
{
 public void fun1();
 public void fun2();
}
class A implements xyz
{
 public void fun1()
 {
  System.out.println("Hello Function 1");
 }
 public void fun2()
 {
  System.out.println("Hello Function 2");
 }
 public void fun3()
 {
  System.out.println("Hello Function 3");
 }
 
 public static void main(String args[])
 {
  A a1=new A();
  a1.fun1();
  a1.fun2();
  a1.fun3();
 }
}


Note : One class can implements more than one interface.

Example :
Class A implements xyz, pqr, abc.
It look like multiple inheritance but it is not actually.

IMP Note :
By default all the elements declared in interface are in public.



Final keyword :

Keyword "final" is used to create constant in Java program. The values of these variables are never changed at runtime.

Example :
final int x=3;
x=5; // error
x=3; // error
x++; // error

IMP Note :
By default the interface variables are public, static and final.

interface ABC
{
 public final static int x=10;
 int y=20;
}
class B implements ABC
{
 public static void main(String args[])
 {
  B b1=new B();
  
  System.out.println("X is "+b1.x);
  System.out.println("Y is "+b1.y);
  
  // b1.X=50;  error
  // b1.Y=100; error
  
  System.out.println("X is "+ABC.x);
  System.out.println("Y is "+ABC.y);
 }
}

Axact

Narendra

Hello, everyone! I am Narendra Bagul founder of Javanotes9. First of all thank you for visiting my blog. Hope you all like my java notes as well. I'm young part time blogger and a Computer Engineering student. I started blogging as a hobby. Now here I'm sharing my little acquired knowledge about my favorite programming language JAVA.

Post A Comment: