D
D
Dima Melnyk2017-01-12 17:51:36
Java
Dima Melnyk, 2017-01-12 17:51:36

Using Interfaces in Java?

Discovered a new topic in Java - interfaces. I tested on simple examples that and how it works. The question arose whether it is correct to use (correctly) use interfaces in this example?
There is an interface Second, classes Test and Tester, which are inherited from this interface

public interface Second {
    void print();
}

public class Test implements Second{    
    public void print() {
        println();
    }

    private void println(){
        System.out.println("123");
    }
}

public class Tester implements Second{
    public static void main(String[] args) {
        Tester tester = new Tester();
        tester.print();
    }
    
    public void print() {
        Test test = new Test();
        test.print();
        System.out.println("++++");
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Alexandrov, 2017-01-13
@dima_meln

Auto RU. You took some very vague example for yourself. Figuratively speaking, the interface is an abstraction.
For example, you have a certain game. The game has vehicles. You are wondering how to make it so that you do not know what kind of transport it is, but at the same time use it confidently.
1) You look at all your classes: car, bus, plane, boat, bicycle.
2) All classes of transport have common features. They can drive forward/backward, steer left/right, signal, etc.
3) Describe an interface with these dedicated public methods. for example

interface Transport{
   void gazuem();
   void tormozim();
   void signalim();
...
}

4) Now it's time to implement this interface. Example:
public class Avtobus implements Transport{    
    public void gazuem() {
        //реализация особенности как едет автобус
    }
    public void signalim() {
        //тут просто школьный Фа-Фа
    }
}
//Велосипед
public class Velosiped implements Transport{    
    public void gazuem() {
        //реализация особенности как будете крутить педали
    }
    public void signalim() {
        //тут колокольчиком Дзинь-Дзинь
    }
}
//Остальные реализации

5) We abstract in the code from the implementations of specific modes of transport, i.e. we work with them as with a black box. For example:
Transport velik = new Velosiped();
Transport avtobus = new Avtobus();
...
Transport samolet = new Samolet();

...
И гдето , например, все виды транспорта попали в коллапс и надо резко посигналить.
velik.signalim(); //Дзинь дзинь
avtobus.signalim(); // Фа-Фа
samolet.signalim();// А тут звуков не будет но вам до лампочки и никаких ошибок не будет
...
//Дальше, например, у игрока есть метод использовать.
//Вам не нужно знать какой именно тип транспорта перед ним, вы просто делаете следующее:
class Player{
...
public void use(Object someObject){
          if(someObject instanceof Transport){
                //Сюда попадет абсолютно любой тип транспорта
                ((Transport)someObject).sadimsya(); //Что там внутри и как оно работает вас уже не интересует
          }
}
...
}

In general, this is what it looks like.

S
Soulkeeper, 2020-09-02
@Soulkeeper31

To better understand what interfaces are for - learn SOLID principles

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question