Core Java Tutorial

Define Java

C vs C++ vs Java

Java Virtual Machine

Java First Program

Java Data Types

Java Tokens

Java Keywords

Java Operators

Operator Precedence

Java Type Casting

Java Statement

Java If statement

Java Switch statement

Java Loops

Java Jumping Statement

Java Arrays 1D

Java Arrays 2D

Java Variable Size Array

Java Vector

Java Math Methods

Java String Methods

Java String Buffer

User-Defined Method

Java Method Overloading

Java Class & Object

Java Constructor

Java Inheritance

Java Interface

Java Packages

Java Multi-threading

Exceptional Handling

File Handling

Java Applets

Java DataBase Connectivity

Page Stats

Visitor: 242

Java Interface

An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a major difference. The difference is that interface defines only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contain only constant values.

Therefore, it is the responsibility of the class that implements an interface to define the code for these methods.

Syntax to declare interface.

interface <interface name> 
{
    [fields declaration];
    [method declaration];
}

Difference between Interface and Abstract Class

  1. An interface cannot implement any methods, whereas an abstract class can.
  2. A class can implement many interfaces but can have only one super class.

Why we use interface then?

Let's say I want you to make an application that should have one method. Method that takes two integer data type parameters and performs some operation on them, returning value is void.

So, you should use a method with two integer parameters and whatever the code is required to perform that operation in that method. It is the way of standardizing the software engineering process where designers give you interfaces and coders write the code. You cannot choose naming convention that suits you, interface is a contract that you must follow.