Sitemap
Shraddhamandekar

Shraddhamandekar

Computer Engineering

Interface In Java

2 min readMay 27, 2020

--

Press enter or click to view image in full size

An interface is a completely "abstract class" that is used to group related methods with empty bodies. we know that multiple inheritance is not supported in java in such cases interface plays great job.

we can’t define method inside interface till java 1.7. From java 1.8 we can also define method inside interface. we can’t create object of interface. Interface is implemented by class and extended by another interface.

import java.lang.*;

public interface Interface_Name {
// Any number of final, static fields
// Any number of abstract method declarations
}

Each method inside the interface is abstract. we can’t create object of interface because for creating object constructor is needed to allocate memory for object and declaration of constructor in not allowed in interface. we can create reference of interface and memory allocation for object will done by class.

Implementing Interface:

interface A
{
public void show();
}
class B implements A
{
public void show()
{
System.out.println("hello");
}
public void display()
{
System.out.println("hi");
}
}
class mainclass
{
public static void main(String args[])
{
A obj=new B();
obj.show();
//In this case if we don't to give access to method
display and only want to give access to interface
method then we can use this.
B obj1=new B();
//with this we can access all
methods of that class.
obj1.show();
obj1.display();
}
}

After implementing interface we have to implement all the methods of interface.

Extending Interface:

interface A
{
void show();
}
Interface B extends A
{
void display();
}
class My implements B
{
void show()
{
//code here
}

void display()
{
//code here
}
}

One interface extends other interface.

Get Shraddhamandekar’s stories in your inbox

Join Medium for free to get updates from this writer.

Types of interface

  1. Marker Interface
  2. Single Abstract Method

Marker Interface is one which don’t have any method inside it. This kind of interface can be use for permission.

Single Abstract Method interface has only one method.

Interface in java 1.8

As we know we can define method inside interface below is syntax to define interface in 1.8.

interface A
{
void add();
default void show()
{
//code here
}
}

Default keyword is necessary to define method inside interface.

java 1.8 also supports static methods inside interface.

interface A
{
public static void show()
{
System.out.println("hi");
}
}
class main_class
{
public static void main()
{
A.show();
}
}

Thank you.

Share with your friends :)

--

--