Смарт контракты

Published 15 October 2018

Interfaces in Java

What is an interface in Java. What is it used for.

What is an interface in Java. What is it used for.

Interface is a software structure that defines the relationship between objects that share a certain behavioral set and are not linked in any other way. Used for multiple inheritance of interfaces in a class, because a class can inherit from only one parent class.

Declaration of an interface is perfomed as follows: first goes the interface keyword and the interface name, after which there may be the extends keyword and the list of interfaces from which the declared interface will be inherited, then the body of the interface is written in curly braces. The interface body consists of constant fields and abstract methods. All interface fields are automatically public final static, so they must be initialized immediately. All interface methods are public abstract. To implement an interface, it must be specified when declaring a class by using the implements keyword. You cannot create an instance of an interface in Java.

Examples of interfaces

Examples of interfaces

interface MyArrow{

int right=1;

int left=2;

int up=3;

int down=4;

}

interface MoveArrow extends MyArrow{

void moveRight();

void moveLeft();

void moveUp();

void moveDown();

}

public class MyClass implements MoveArrow{

public void moveRight(){

System.out.println(right);

}

public void moveLeft(){

System.out.println(left);

}

public void  moveUp(){

System.out.println(up);

}

public void moveDown(){

System.out.println(down);

}

 

public static void main(String args[]){

MyClass stgf=new MyClass();

stgf.moveUp();

}

}

Basic information about interfaces in Java

Basic information about interfaces in Java

  • interface — the keyword for creating an interface;
  • it is impossible to create an instance of an interface - interface doesn't have a builder;
  • provides total abstraction;
  • cannot be a subclass of another class;
  • the implements keyword is used by classes to implement the interface;
  • the class that implements the interface must implement all of its methods.

Advantages and disadvantages of interfaces in Java

Advantages and disadvantages of interfaces in Java

  • provides multiple inheritance of interfaces in a class;
  • is used to create a hierarchy in a project;
  • removing interface methods in the later stages of the project will result in a compilation error in all classes that implement the interface.
Votes 0, average rating 0

Contents