C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programming language

Java Interfaces with its properties, implementation and Example

Submitted by Amit Shukla, on June 10, 2017

Learn: Interface in java, this article will explain about interfaces in java and their properties.

In Java programming interfaces are just a like class which contains methods with empty implementation and constant variables. All these methods are “public and abstract” by default. Since interfaces are abstract in nature so they cannot directly instantiate. Hence we have to use implement keyword to define interface.

Interference is similar to abstract classes but the major difference between these is that interface has all method abstract but in case of abstract classes must have at least one abstract method.

Properties of interface

  1. It always contains final data members.
  2. It cannot be instantiated.
  3. All methods of interface are abstract and public in nature.
  4. The class which implements interface need to provide functionality for the methods declare in the interface.
  5. One can use interface to implement PM (Partial multiple inheritance) and DMD (Dynamic memory dispatch).
  6. Interface always implements in derived class.

Declaration of Interface

import java.util.*;

interface interfacename
{
    //define abstract methods
    //define constants
} 

Example of defining of inheritance:

Correct method - 1

interface interfaceone
{
}

interface interfacetwo extends interfaceone
{
}

Correct method - 2

interface interfaceone
{
}

class classone
{
}

class clastwo extends classone implements interfaceone
{
}

Incorrect method - 1

interface interfaceone
{
}

interface interfacetwo implements  interfaceone
{
}

Incorrect method - 2

interface interfaceone
{
}

class classone
{
}

class clastwo implements interfaceone extends classone 
{
}

Consider the program:

import java.util.*;

interface student
{
	void get();
	void put();
}

class admin implements student
{
	Scanner sc=new Scanner(System.in);
	private int rollno;
	private String name;
	public void get()
	{
		System.out.print("Enter name of student : ");
	    name=sc.nextLine();
	    System.out.print("Enter roll number of student : ");
	    rollno=sc.nextInt();

	}
	public void put()
	{
		System.out.println("Name of student is "+name);
		System.out.println("Roll number of Student is "+rollno);
	}
}

class ExInterfaces
{
	public static void main(String arg[])
	{
		admin S=new admin();
		S.get();
		S.put();
	}
}

Output

First Run:
Enter name of student : Ankit Yadav
Enter roll number of student : 1004
Name of student is Ankit Yadav
Roll number of Student is 1004


Second Run:
Enter name of student : Abhishek Kataria
Enter roll number of student : 1003
Name of student is Abhishek Kataria
Roll number of Student is 1003








COMMENTS