Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Simplified Concept on What Is Interface In Java: Detailed Facts In 5 Minutes

Introduction to What Is Interface In Java

An interface is a reference type in java and an interface is like a simple java Class that has static constants and abstract methods.

Since java does not support multiple inheritances directly, Java uses to interface to Implement multiple inheritances. A java class can implement multiple Java interfaces.

Interfaces provide a way to create a set of classes that have rather a different purpose but few similar methods. All methods in an interface are public and abstract. So an interface is a pure abstract class.

An interface is a class blueprint, which can be declared using the keyword interface. Interfaces can contain only constants and abstract methods (methods with only signatures nobody).

Like abstract classes, Interfaces can not be instantiated, they can only be implemented by classes or extended by other interfaces. The interface is a common way to achieve full abstraction in Java.

Java does not support Multiple Inheritance, but it is similar to an abstract class that a class can implement more than one interface, but it contains only abstract methods.

Interfaces are created using keyword interface instead of keyword class We use keyword implements while implementing an interface (similar to extending a keyword extend class)

Syntax:

class ClassName extends Superclass implements Interface1, Interface2, ....

All interface methods are implicitly public and abstract. Use of the abstract keyword before each method is optional.

An interface may contain final variables.

A class can extend only one other class, but it can implement any number of interfaces.

When a class implements an interface it has to give the definition of all the abstract methods of the interface, else it can be declared as an abstract class An interface reference can point to objects of its implementing classes.

Generalization and Specialization

To implement the concept of inheritance in an OOPs, one must first identify the similarities between the different classes to arrive at the base class.

This process is called Generalization to identify the similarities between different classes. Generalization is the process by which shared characteristics are extracted from two or more classes and combined into a generalized superclass.

When a child’s class needs to be created from two or more superclasses, the phenomenon is called multiple inheritances.

Java does not support multiple inheritances directly(meaning java classes can not have more than one superclass like Class A extends B extends C {} is illegal in java) but with the interface, we can do similar approach.

In real life, we can create several distinct classes to support multiple inheritances. In java, the interface is a reserved keyword that implies an interface consists of a set of instance method interfaces without any implementation.

A class can implement an interface by providing an implementation for each of the methods specified by the interface.

The class which is trying to implement the method must state to the java virtual machine that this class is going to implement some interface by the keyword “implements”.Like class circle implements Drawable{….}.

Even though the interfaces are not exact classes, they can be compared to abstract classes in the sense that we can not create objects from the interface or abstract class but can be used as a base for making subclasses.

Along with the methods, an interface may also contain constants, default methods, and static methods. The method body exists for only default methods and static methods.

So Interface allows the creator of the classes to establish the form of the classes, method names, argument lists, and return types but nobodies.

It is possible to add initialized definitions for primitives but these become compile-time constant. They are static and final thus no storage to be created for the actual object.

An interface says “this is what all classes that implement this particular interface shall look like. Any code that uses a particular interface knows what methods may be called for the interface.

So interface is used to establishes a protocol between classes. Creating an interface -instead of class, we need to use the word called Interface. It can be public or friendly.”

For primitive types, they become compile-time constant which is equivalent to create an enum in java. We can create an interface containing all over enumeration identifiers providing a unique integer value. This is not ideal.

So if we say that a particular class implements an interface. It is a promise that we have included methods in our class corresponding to each of the methods in the definition of the interface.

Hence, the class implements an interface that needs to define the methods. The interface lacks instance variables and the method body does not have any code in it. Interface says what the class must do.

Syntax of the interface:


interface interfaceName{
//variables and methods
}
//another one
interface interfaceName[extends Name1]{
//variables and methods
}
 

One Example for interface

We need to use the interface keyword to define an interface

//FileName: MyInterface.java
import java.lang.*;
//any number of import statements
public interface MyInterface{
//any number of final and static fields
public abstract doSomething();
public abstract readSomething();
//any number of abstract method declaration
}
 

The interface will have the properties

  • An interface is implicitly abstract. We do not need to use the abstract keyword declaring interface.
  • Each method in an interface is also implicitly abstract so the abstract keyword is not needed.
  • Methods in an interface are implicitly public.

Data variable in an interface

An interface can contain only constants. That means the variables are-

  • public
  • final
  • static

As they are constants, they cannot be changed by the subclasses.

Syntax-

public static final type variable name= value;

What is Implementing an Interface?

While a class implements an interface, it makes a contract with the interface to perform specific behaviour of the interface. If the class fails to perform all behaviours of the interface, the class must declare itself abstract.

A class uses the implements keyword to implement an interface. The implement keyword is placed in the class deceleration following the extends portion of the deceleration.

An interface can extend another interface but not a class. Java does not support multiple inheritances but it supports multiple interface inheritance.

The class has to override all the abstract methods defined in the interface. There are few rules around. They are as follows:

  • Checked Exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclass of those declared by the interface method.
  • The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.
  • An implementation class itself can be abstract and if so, the interface methods need not be implemented.
  • A class can implement more than one interface at a time but can extend only one class.
  • An interface can extend to another interface.

Class structure implementing the interface:


class MyClass extends SuperClass implements interface1,interface2,interface3......intefaceN{
//body of the class
}
 

The member variables present in an interface should be static and final.
Example:


interface Pet{
public void test();
}
public class Cat implements Pet{
public void test()
{
System.out.println("Interface method implemented in the child class");
}
public static void main(String args[])
{
Pet p=new Cat();
p.test();
}
}
 

The output of the code:
$javac Cat.java
$java -Xmx128M -Xms16M Cat
Interface method implemented in the child class

Accessing implementing class objects through interface reference:-

A variable can be declared as an object reference. This variable uses an interface instead of a class type. If an instance of any class implements the declared interface can also be refused by such variable. When a call is made through one of this reference, the actual correct version is called based on the actual instance.

One more example:


interface Area{
    final static float PI=3.14F;
    float compute(float x,float y);
}
class Rectangle implements Area{
    public float compute(float x,float y)
    {
        return x*y;
    }
}
class Circle implements Area{
    public float compute(float x,float y)
    {
        return PI*x*y;
    }
}
public class MYInterfaceTest{
    public static void main(String args[])
    {
        Rectangle rect=new Rectangle();
        Circle cir=new Circle();
        Area area;
        area=rect;
        System.out.println("Area of the rectangle "+area.compute(10,20));
        area=cir;
        System.out.println("Area of the rectangle "+area.compute(10,20));
    }
}
 

The output of the code:
$javac MYInterfaceTest.java
$java -Xmx128M -Xms16M MYInterfaceTest
Area of the rectangle 200.0
Area of the rectangle 628.0

A more real-time example:

Assume that there are two classes for an organization

  • One PermanentEmployee
  • One Vendor Employee

Now each class has their unique components called Qualification,MainCompany,Current_Project,Current_Project,Experience(),Next_Project().

class PermanentEmployee class VendorEmployee
Qualification MainCompany
Current Project CurrentProject
Experience() Next_Project()
 Class Organization 
 …… 
 Resume 

Now if the Organization wants to have a resume for both types of Employees. So the Organization class define an interface called Resume.


interface Resume{
....
void EmpResume();
}
class  PermanentEmployee Extends Employee implements Resume{
Qualification;//member variables
Current_Project;//member variables
Experience(){};//member function
public void EmpResume()
{
....
//code to implement the resume
}
}
class VendorEmployee implements Resume{
MainCompany;//member variables
Current_Project;//member variables
Next_Project(){}//member function
public void EmpResume()
{
....
//code to implement the resume
}
}
//so the implementation of the code goes like
PermanentEmployee pe=new PermanentEmployee();
pe.EmpResume();
VendorEmployee ve=new VendorEmployee();
ve.EmpResume();
//Futher more we can implement an array of Resume. This is possible as both implement Resume hence they become same type.
Resume listOfResume=new Resume[10];
listOfResume[0]=new PermanentEmployee;
listOfResume[0]=new VendorEmployee;
....
.....

Interface methods

Interface methods are those methods that are abstract methods appearing in the interface. If a class implements an interface but does not implement one or more of the interface methods, the whole class becomes an abstract class and can not be instantiated.

Methods are abstract in the interface. So they do not have anybody. The methods main content parameter list followed by the semicolon. All methods are public and have an abstract modifier. A static method cannot be declared inside an interface.

The interface of a method consists of the name of the method, it returns type and number and types of its parameters.

All methods present in an interface are public by default. This means when we implement an interface, we need to define the methods.

This is the reason why we need to define them as public. Otherwise a default or friendly will restrict the accessibility of the method during inheritance.(not allowed in java).

A class must define all the methods of the interfaces it is implementing. Additionally, the class may define extra methods of its own. These methods are not part of the interfaces it is implementing. These extra methods are called non-interface methods.


interface MyInterface{
public abstractvoid function1();
public abstractvoid function2();
}
class class1 implements MyInterface{
public void function1(){
...
...
}
}
class class2 extends class1{
public void function2(){
...
...
}
}

The interface contains two methods function1() and function2().class1 implements the interface but does not contain the function2() which is a part of the interface. This means that class1 becomes an abstract class.

It can not be instantiated. However, once we create a subclass class2 of class1 and define function2(). That means class2 has successfully implemented all methods of interface-MyInterface.So class2 can be instantiated.
When to use interface and when to use an abstract class?
We need to use an abstract class when a template needs to be defined for a group of subclasses. But we need to use interface when a role needs to be defined for other classes regardless of the inheritance tree of these classes.

The class can not implement two interfaces in java that have methods with the same name but different return types.

Difference between class and Interface:

Sl NoClassInterface
1we can instantiate the class and create an object from itWe can not instantiate an Interface and create an object from it.
2the class contains concrete methods and constructors.The interface can not contain any concrete methods as well as constructors.
3Access Specifiers can be public, protected, privateThe only specifier is public
4Members can be of different typesAll members are the abstract method and final- constant variable.
5The class can contain instance fieldsInterfaces can not contain instance fields. The only fields that can appear in an interface must be declared both static and final
6A class can extend to other classAn interface can extend to one or multiple interfaces. A class can not extend to an interface, it needs to be implemented

How Interface Similar to class:

  1. Just like a class, an interface can contain any number of methods and variables.
  2. An interface is written in a file with extension .java similar to the class name of the interface matching with the name of the file.
  3. Just like class the byte code of an interface is placed in a .class file.
  4. Like classes, interfaces appear in packages, and their corresponding byte code file must be in a directory structure that matches the package name.

How the interface can share member variables:

The interface can be used to declare a set of constants that can be used in different classes. Since such interfaces do not contain methods. we do not need to implement any methods. The variables treated as constant will be available to any class that implements the interface. The values can be used in any method, part of any variable deceleration, or anywhere.

interface Response{
static final int yes=1;
static final int No=2;
}
class Enquire implements Response{
public int ask(){
System.out.println("Have you seen google -Type your response: yes-1 No-2");
int type=0;
try{
type=System.in.read();
}
catch(Exception e){}
return type;
}
}
public class MyServey implements Response{
public static void main(String args[])
{
Enquire myResp=new Enquire();
reply(myResp.ask());
reply(myResp.ask());
}
static void reply(int type)
{
switch(type){
case yes:
System.out.println("You have seen google.Thanks!");
break;
case No:
System.out.println("You have not seen google.Thanks!");
break;
default:
System.out.println("You have given a valid input!");
}
}
}

How inheritance can be seen in the interface:

Classes can have multiple interfaces implemented. Similarly, interfaces also have a chain of inheritance that is an interface that can be derived from another interface.


import java.awt.Graphics;
interface BoxDimention{
int top;
int bottom;
int left;
int right;
}
interface DrawBox extends BoxDimention{
void draw(int a,int b,int c,int d);
}
class Box implements BoxDimention{
public void Area(){
....
//code
}
}
class ShowBox implements BrawBox{
int x,y,z,w;
void draw(int a,int b,int c,int d){
x=a;
y=b;
z=c;
w=d;
void paint(Graphics g){
g.drawRect(x,y,z,w);
}
}
}
 

The Box just needs access to the constants and would implement BoxDimension while the class ShowBox needs access to the draw() method and would implement DrawBox.

Multiple inheritances through the interface

Multiple inheritances are allowed for interfaces. if we need to do both, to ensure the box as well as draw the box then-


import java.awt.Graphics;
interface BoxDimention{
int top;
int bottom;
int left;
int right;
}
interface DrawBox{
void draw(int a,int b,int c,int d);
}
interface Box extends BoxDimention,DrawBox{
void area();
}
class ShowBox implements Box{
//code for area
//code for draw
}
 

Nested interface

A nested interface is an interface that is declared inside the body of a class or interface. The top-level interface is not a nested interface.

Interface modifiers

The top-level interface can have modifiers only abstract and public. The visibility of the top-level interface can be-

  • Package level
  • Public

If no visibility modifier is used by the default modifier is package level.

Variable type is given by the interface

We can declare a variable whose type is given by the interface. If Drawable is an interface and if Line and Circle class that implements Drawable then we can say:


Drawable figure;//declare a variable of type interface-Drawable.It can refer to any object 
//that implement Drawable interface.
figure=new Line();// figure refers to Line object
figure.draw(g);//calls the draw() method of class Line
figure=new Circle();// figure refers to Circle object
figure.draw(g);//calls the draw() method of class Circle
 

type can be used to declare variables. A type can also be used to specify the type of a parameter in a subroutine or the return type of a function. In java, a type can be either a class, an interface, or a primitive type.

Things to remember in the interface:

  • Java classes can implement multiple Java interfaces.
  • All variables declared in an interface are constants.
  • Interface methods must end with a semicolon(;).
  • It is necessary to implement all the methods declared in the interface.
  • Classes also should override all methods declared in the interface.
  • The interface allows sending a message to an object without concerning which class it belongs.
  • The class needs to provide functionality for the methods declared in the interface.
  • All methods in an interface are implicitly public and abstract.
  • An interface can not be instantiated.
  • An interface reference can point to objects of its implementing classes.
  • An interface can extend to one or many interfaces.
  • A class can extend to one class but implement any number of interfaces.
  • An interface can not implement another interface. It has to extend another interface if needed.
  • An interface that is declared inside another interface is called a nested interface.
  • At the time of declaration, interface variables must be initialized. Otherwise, the compiler will throw an error message.
  • Any object created from the concrete class will also have the interface method.
  • While the interface is allowed to extend to other interfaces, if sub-interfaces can not define the method of the super interface, the subinterface is still been an interface.
  • An interface can not extend to a class. This would violate the rule of an interface(Interface can have only abstract methods and constants).

Do Interfaces Seriously Inherit the Item Course (the Cosmic Superclass) In Java?

Well… the answer is NO. An interface is unable to inherit from a class in Java, not at the very least directly.

So, we can securely say that interfaces don’t inherit from the Object class. Ok… so how can they do that indirectly? We know that interfaces can have courses declared as customers as effectively just like they can have constants.

This kind of a class is named a member class and like constants, all the member classes of an interface would be static and general public. And that static member class (like any other course in java) inherits Object class.

But, how are we equipped to compile code possessing Object strategy calls on the references of an interface form in Java?

We all know that the item of the employing class (and as a result of its type) will be assigned to only at run time and we can compile code only if the compiler finds a process of that signature in the declared sort (possibly declared immediately or inherited from superclasses).

This is suitable for lessons in Java, but only partially appropriate for interfaces in Java. Amazed? Let’s check out to comprehend what internally takes place in the circumstance of interfaces.

The Java Language Specification suggests that the associates of an interface are those people which are declared in the interface and these are inherited from direct super interfaces.

If an interface has no immediate super interface then the interface implicitly declares a community summary member system corresponding to each general public occasion system declared in the Item class, unless of course a technique with the same signature, same return variety, and a compatible throws clause is explicitly declared by that interface.

This is what will make the signatures of the Item solutions accessible to the compiler and the code compiles with no mistake.

Don’t forget if the interface attempts to declare a general public instance system declared ‘final’ in the Item course then it’s going to final result in a compile-time mistake.

For example, ‘public last Course getClass()’ is a community instance technique declared ‘final’ in the Object course, and therefore if an interface tries to declare a system with this signature then the compilation will are unsuccessful.

Is this Inheritance of Item solutions by the Interfaces?

No. This can not be termed as ‘Object procedures remaining inherited by the Interfaces’. This is just a specific treatment offered to the interfaces in Java.

In this situation, all the competent (public instance) Item class procedures are declared as community summary, which is not inheritance. Right?

In an inheritance, we get the definition of the technique as perfectly and the non-abstract approaches are not inherited as ‘abstract’.

But an interface in Java is unable to have any of these two – definitions or non-abstract approaches. Therefore, the designers of Java experienced to feel of an option.

What’s more, only public occasion solutions are implicitly declared in the interfaces, and what about other methods – for case in point, protected Object clone() and secured void finalize()? In the case of inheritance, they are also inherited by the subclasses.

Thus, we see that it is not precisely the inheritance of the Item course by the interfaces. An interface can not inherit a course for the uncomplicated reason that interfaces can only have abstract procedures (i.e., they are not able to have the entire body).

Make sure you should not say that we can have an abstract course having only abstract techniques that can be inherited safely by interfaces We will greater have an interface in that case.

Example: a basic Java software displaying the Item process obtain on interface ref variety.

package test
public class TestInterfaceDemo
public static void main(String[] args)
TestInterface testInterface = new TestInterfaceImpl()
//... calling Object class process - toString - Alright
System.out.println(testInterface.toString())
//... calling the interface technique - testMethod - Ok
testInterface.testMethod()
//... calling the implementing class method - implClassMethod - error
//testInterface.implClassMethod()
//... calling the same approach after casting the reference - Okay
((TestInterfaceImpl)testInterface).implClassMethod()
}
}
package Test;
public class TestInterfaceImpl implements TestInterface{
public void testMethod(){
System.out.println("Examination Technique if the Interface")
public void implClassMethod(){
system.out.println("Exam Interface Impl Course Technique")
}
}

Output:-

take a look at [email protected] (variable… will in all probability be diff for you)
Test Approach if the Interface
Examination Interface Impl Class System

If we uncomment the line ‘//test interface.implClassMethod()’ for accessing a method of the applying class which is not a member of the interface sort then expectedly we get a compiler mistake:-

Error(14,23): approach implClassMethod() not observed in interface examination.TestInterface

The compiler does not know the type of the assigned item and hence can not solve the signature of the system contact on the declared reference kind in the course of compilation and consequently report an error. I hope the above explanation assists.

Further Example

Interface Printer {
Void display ( int x);
}
Class Laptop implements Printer {
Public void display ( int x)
{
System.Out.println(" laptops printer"+" port"+x);
}
}
Class desktop implements printer {
public void display ( int x){
System. Out.printh(" desktopss printer"+" port"+x);
     }
}

Class printer tester:-


public static void main(String args[ ]){
Printer P1= new Laptop( );
Printer P2= new Desktop( );
P1. display (8080);
P2. display (7880);
Printer P3;
P3 = P1;
P3.display(5555);
P3 = P2
P2.display(8888);
 }
}

 

 

The post Simplified Concept on What Is Interface In Java: Detailed Facts In 5 Minutes appeared first on Tech Travel Hub.



This post first appeared on Tech Travel Hub, please read the originial post: here

Share the post

Simplified Concept on What Is Interface In Java: Detailed Facts In 5 Minutes

×

Subscribe to Tech Travel Hub

Get updates delivered right to your inbox!

Thank you for your subscription

×