Зачем нужен interface java

Зачем нужен interface java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Interfaces

There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a «contract» that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group’s code is written. Generally speaking, interfaces are such contracts.

For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.

The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group’s software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.

Читайте также:  Отобразить html код странице

Interfaces in Java

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson.

Defining an interface is similar to creating a new class:

public interface OperateCar < // constant declarations, if any // method signatures // An enum with values RIGHT, LEFT int turn(Direction direction, double radius, double startSpeed, double endSpeed); int changeLanes(Direction direction, double startSpeed, double endSpeed); int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, double speedOfCar); int getRadarRear(double distanceToCar, double speedOfCar); . // more method signatures >

Note that the method signatures have no braces and are terminated with a semicolon.

To use an interface, you write a class that implements the interface. When an instantiable class implements an interface, it provides a method body for each of the methods declared in the interface. For example,

public class OperateBMW760i implements OperateCar < // the OperateCar method signatures, with implementation -- // for example: public int signalTurn(Direction direction, boolean signalOn) < // code to turn BMW's LEFT turn indicator lights on // code to turn BMW's LEFT turn indicator lights off // code to turn BMW's RIGHT turn indicator lights on // code to turn BMW's RIGHT turn indicator lights off >// other members, as needed -- for example, helper classes not // visible to clients of the interface >

In the robotic car example above, it is the automobile manufacturers who will implement the interface. Chevrolet’s implementation will be substantially different from that of Toyota, of course, but both manufacturers will adhere to the same interface. The guidance manufacturers, who are the clients of the interface, will build systems that use GPS data on a car’s location, digital street maps, and traffic data to drive the car. In so doing, the guidance systems will invoke the interface methods: turn, change lanes, brake, accelerate, and so forth.

Interfaces as APIs

The robotic car example shows an interface being used as an industry standard Application Programming Interface (API). APIs are also common in commercial software products. Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product. An example would be a package of digital image processing methods that are sold to companies making end-user graphics programs. The image processing company writes its classes to implement an interface, which it makes public to its customers. The graphics company then invokes the image processing methods using the signatures and return types defined in the interface. While the image processing company’s API is made public (to its customers), its implementation of the API is kept as a closely guarded secret—in fact, it may revise the implementation at a later date as long as it continues to implement the original interface that its customers have relied on.

Читайте также:  Html css название шрифта

Источник

What Is an Interface?

As you’ve already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object’s interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the «power» button to turn the television on and off.

In its most common form, an interface is a group of related methods with empty bodies. A bicycle’s behavior, if specified as an interface, might appear as follows:

To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle ), and you’d use the implements keyword in the class declaration:

class ACMEBicycle implements Bicycle < int cadence = 0; int speed = 0; int gear = 1; // The compiler will now require that methods // changeCadence, changeGear, speedUp, and applyBrakes // all be implemented. Compilation will fail if those // methods are missing from this class. void changeCadence(int newValue) < cadence = newValue; >void changeGear(int newValue) < gear = newValue; >void speedUp(int increment) < speed = speed + increment; >void applyBrakes(int decrement) < speed = speed - decrement; >void printStates() < System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear); >>

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

Note: To actually compile the ACMEBicycle class, you’ll need to add the public keyword to the beginning of the implemented interface methods. You’ll learn the reasons for this later in the lessons on Classes and Objects and Interfaces and Inheritance.

Источник

Зачем нужны интерфейсы?

Java-университет

Зачем нужны интерфейсы? Зачем нужно наследование интерфейсов? Зачем нужен полиморфизм? Для тех, кто почитал и понял как делать интерфейсы, но не понял зачем.

Дисклеймер: В этой статье и последующих, нейминги классов и методов будут приведены на русском языке.

Читайте также:  Скрипт java базы данных

Когда речь заходит о принципах объектно-ориентированного программирования (ООП): полиморфизм, наследование и инкапсуляция, полезно приводить аналогии из реального мира. Большой плюс ООП в том, что мы в программе можем смоделировать часть реальной вселенной. Смоделируем семью Ивановых: Папа, Мама и мальчик Петя. От Папы Петя унаследовал привычку прихлюпывать когда пьет чай, а от Мамы он унаследовал привычку поджимать губы во время чтения. Если попытаться реализовать эту ситуацию в программу, то у нас получиться три класса:

 class Папа class Мама class Петя 

У Папы и Мамы есть привычки, которые нужно передать Пете. Привычки — это какие-то действия — так что лучше всего реализовать их в программном мире как методы: Сначала Папа:

 class Петя extends Папа, Мама < @Override public void прихлюпывать() < System.out.println("Хлюп"); >@Override public void поджимать() < System.out.println("Поджать губки"); >> 

Зачем нужны интерфейсы? - 1

То есть унаследовать Петю от Папы и Мамы одновременно. Если так написать, то компилятор будет ругаться, потому что в Java нельзя реализовать множественное наследование классов. К слову, в С++ можно, а вот в Java нельзя, потому что с множественным наследованием могут возникнуть большие проблемы: подробно пишут в интернете. Что бы обойти это «нельзя», в Java есть интерфейсы. И для привычек мы придумаем свой интерфейс. Даже два: Выглядеть они будут так:

 public interface ПривычкиПапы < public void прихлюпывать(); >public interface ПривычкиМамы

В интерфейсе мы только описали привычки, но не описали что они конкретно делают, потому что конкретную реализацию мы пропишем в классах. Сначала отдадим Папе и Маме их законные привычки.

 class Папа implements ПривычкиПапы < @Override public void прихлюпывать() < System.out.println("Хлюп"); >> class Мама implements ПривычкиМамы < @Override public void поджимать() < System.out.println("Поджать губки"); >> 
 class Петя implements ПривычкиПапы, ПривычкиМамы < @Override public void прихлюпывать() < System.out.println("Хлюп"); >@Override public void поджимать() < System.out.println("Поджать губки"); >> 

Зачем нужны интерфейсы? - 2

То есть множественная реализация (чаще говорят имплементация) в Java вполне возможна. Смысл интерфейсов теперь должен быть понятен – в Java с помощью интерфейсов можно реализовать множественное наследование. Если развивать ситуацию дальше, например: ведь у Папы и Мамы наверняка есть привычки, которые они не передали Пете, да и у Пети могут быть свои личные привычки. Как эту жизненную Санта-Барбару перенести в плоскость Java вы узнаете в следующих сериях. Это не единственный пример для понимания интерфейсов.Если не читали следующие статьи, то обязательно прочтите: Интерфейсы в Java (если не открыто, можно выйти из профиля или прочитать в режиме — инкогнито) Для чего в Java нужны интерфейсы — тут реализуйте все примеры из статьи и поизменяйте методы и в интерфейсах и в калассах: наименования методов, сигнатуры (то что метод принимает на вход), типы вывода методов. Разберитесь самостоятельно: — с разницей при имплементации интерфейса с классом и абстрактным классом; — дефолтными методами.

Источник

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