Java класс имплементирующий интерфейс

Java implements Keyword

An interface is an abstract «class» that is used to group related methods with «empty» bodies:

To access the interface methods, the interface must be «implemented» (kinda like inherited) by another class with the implements keyword (instead of extends ). The body of the interface method is provided by the «implement» class:

// interface interface Animal < public void animalSound(); // interface method (does not have a body) public void sleep(); // interface method (does not have a body) >// Pig "implements" the Animal interface class Pig implements Animal < public void animalSound() < // The body of animalSound() is provided here System.out.println("The pig says: wee wee"); >public void sleep() < // The body of sleep() is provided here System.out.println("Zzz"); >> class MyMainClass < public static void main(String[] args) < Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); >> 

Definition and Usage

The implements keyword is used to implement an interface .

The interface keyword is used to declare a special type of class that only contains abstract methods.

To access the interface methods, the interface must be «implemented» (kinda like inherited) by another class with the implements keyword (instead of extends ). The body of the interface method is provided by the «implement» class.

Notes on Interfaces:

  • It cannot be used to create objects (in the example above, it is not possible to create an «Animal» object in the MyMainClass)
  • Interface methods does not have a body — the body is provided by the «implement» class
  • On implementation of an interface, you must override all of its methods
  • Interface methods are by default abstract and public
  • Interface attributes are by default public , static and final
  • An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?

To achieve security — hide certain details and only show the important details of an object (interface).

Java does not support «multiple inheritance» (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).

Читайте также:  Редактирование изображений на php

Multiple Interfaces

To implement multiple interfaces, separate them with a comma:

Example

interface FirstInterface < public void myMethod(); // interface method >interface SecondInterface < public void myOtherMethod(); // interface method >// DemoClass "implements" FirstInterface and SecondInterface class DemoClass implements FirstInterface, SecondInterface < public void myMethod() < System.out.println("Some text.."); >public void myOtherMethod() < System.out.println("Some other text. "); >> class MyMainClass < public static void main(String[] args) < DemoClass myObj = new DemoClass(); myObj.myMethod(); myObj.myOtherMethod(); >> 

Read more about interfaces in our Java Interface Tutorial.

Источник

Implementing an Interface

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. By convention, the implements clause follows the extends clause, if there is one.

A Sample Interface, Relatable

Consider an interface that defines how to compare the size of objects.

public interface Relatable < // this (object calling isLargerThan) // and other must be instances of // the same class returns 1, 0, -1 // if this is greater than, // equal to, or less than other public int isLargerThan(Relatable other); >

If you want to be able to compare the size of similar objects, no matter what they are, the class that instantiates them should implement Relatable .

Any class can implement Relatable if there is some way to compare the relative «size» of objects instantiated from the class. For strings, it could be number of characters; for books, it could be number of pages; for students, it could be weight; and so forth. For planar geometric objects, area would be a good choice (see the RectanglePlus class that follows), while volume would work for three-dimensional geometric objects. All such classes can implement the isLargerThan() method.

If you know that a class implements Relatable , then you know that you can compare the size of the objects instantiated from that class.

Implementing the Relatable Interface

Here is the Rectangle class that was presented in the Creating Objects section, rewritten to implement Relatable .

public class RectanglePlus implements Relatable < public int width = 0; public int height = 0; public Point origin; // four constructors public RectanglePlus() < origin = new Point(0, 0); >public RectanglePlus(Point p) < origin = p; >public RectanglePlus(int w, int h) < origin = new Point(0, 0); width = w; height = h; >public RectanglePlus(Point p, int w, int h) < origin = p; width = w; height = h; >// a method for moving the rectangle public void move(int x, int y) < origin.x = x; origin.y = y; >// a method for computing // the area of the rectangle public int getArea() < return width * height; >// a method required to implement // the Relatable interface public int isLargerThan(Relatable other) < RectanglePlus otherRect = (RectanglePlus)other; if (this.getArea() < otherRect.getArea()) return -1; else if (this.getArea() >otherRect.getArea()) return 1; else return 0; > >

Because RectanglePlus implements Relatable , the size of any two RectanglePlus objects can be compared.

Читайте также:  Когда появился язык программирования kotlin

Note: The isLargerThan method, as defined in the Relatable interface, takes an object of type Relatable . The line of code, shown in bold in the previous example, casts other to a RectanglePlus instance. Type casting tells the compiler what the object really is. Invoking getArea directly on the other instance ( other.getArea() ) would fail to compile because the compiler does not understand that other is actually an instance of RectanglePlus .

Источник

Интерфейсы в Java и немного о полиморфизме

Что такое интерфейс Java и каким он бывает. Что такое функциональный интерфейс. Разбираем на примерах.

Интерфейс – это контракт, в рамках которого части программы, зачастую написанные разными людьми, взаимодействуют между собой и со внешними приложениями. Интерфейсы работают со слоями сервисов, безопасности, DAO и т.д. Это позволяет создавать модульные конструкции, в которых для изменения одного элемента не нужно трогать остальные.

Новички часто спрашивают, чем интерфейс отличается от абстрактного класса. Интерфейсы в Java компенсируют отсутствие множественного наследования классов. У класса-потомка может быть только один абстрактный класс-родитель, а вот интерфейсов класс может применять (имплементировать) сколько угодно.

Интерфейс на Java объявляют примерно так же, как и класс:

public interface MyInterface < void do_something()< // . > default void say_goodbye(String userName) < System.out.println("Пока, "+userName+"! Заходи ещё."); > > 

В имплементирующем интерфейс классе должны быть реализованы все предусмотренные интерфейсом методы, за исключением методов по умолчанию.

Методы по умолчанию впервые появились в Java 8. Их обозначают модификатором default. В нашем примере это метод say_goodbye, реализация которого прописана прямо в интерфейсе. Дефолтные методы изначально готовы к использованию, но при необходимости их можно переопределять в применяющих интерфейс классах.

Читайте также:  Index php view category

Функциональный интерфейс Java

Если у интерфейса только один абстрактный метод, перед нами функциональный интерфейс. Его принято помечать аннотацией @FunctionalInterface, которая указывает компилятору, что при обнаружении второго абстрактного метода в этом интерфейсе нужно сообщить об ошибке. Стандартных (default) методов у интерфейса может быть множество – в том числе принадлежащих классу java.lang.Object.

Как выглядит функциональный интерфейс на Java:

@FunctionalInterface public interface GaMechanic < void new_deck(); default int deal_cards(int num_of_players) < // тело метода >default int check_your_cards(int[] hand) < //. >default int battle(Card player1_Card, Card player2_Card) < //. >> 

Функциональные интерфейсы появились в Java 8. Они обеспечили поддержку лямбда-выражений, использование которых делает код лаконичным и понятным:

button.setOnAction(event -> // если происходит событие System.out.println("Обрабатываем нажатие кнопки.")); 

В той же версии появились пакеты встроенных интерфейсов: java.util.function и java.util.stream.

Реализация интерфейсов классами Java

Допустим, есть интерфейс Edible, которым пользуются классы Fruit, Vegetable, Fish. Экземпляры этих классов можно создавать так:

Edible a1 = new Fruit("Яблоко", “Антоновка”); Edible a2 = new Fish("Нерка слабосолёная", “Тихий океан”, 150); 

Хорошим тоном считается давать интерфейсам названия с окончанием -able/-ible — это показывает, что с объектами, имплементирующими интерфейс, можно что-то делать: Edible (можно есть), Moveable (можно двигать), Clickable (реагирует на клик) и т.д.

Обратите внимание на разницу в конструкторах: для фруктов задаём название и сорт, для рыбы – название, район вылова и вес порции в граммах. Но ссылки на оба объекта храним в переменных одного типа – «Съестное».

Интерфейсы и полиморфизм

Пример выше иллюстрирует один из трех основополагающих принципов ООП — полиморфизм. Мы раскрыли одно и то же явление — съедобность — через несколько классов, свойства и методы которых частично отличаются. Представление разных форм одного явления — это и есть полиморфизм. Если нужно, такую систему всегда можно расширить и скорректировать. В нашем случае — добавить новые виды съестного и методы их приготовления.

В Java полиморфизм можно реализовать через:

  • наследование — с переопределением параметров и методов базового класса;
  • абстрактные классы — шаблоны для раздельной реализации в разных классах;
  • интерфейсы — для имплементации классами.

Интерфейс выручает в ситуации, когда при создании переменной мы не знаем, объект какого класса ей будет присвоен.

Источник

Оцените статью