Answer the question
In order to leave comments, you need to log in
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
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();
...
}
public class Avtobus implements Transport{
public void gazuem() {
//реализация особенности как едет автобус
}
public void signalim() {
//тут просто школьный Фа-Фа
}
}
//Велосипед
public class Velosiped implements Transport{
public void gazuem() {
//реализация особенности как будете крутить педали
}
public void signalim() {
//тут колокольчиком Дзинь-Дзинь
}
}
//Остальные реализации
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(); //Что там внутри и как оно работает вас уже не интересует
}
}
...
}
To better understand what interfaces are for - learn SOLID principles
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question