Naucz się Java · lekcja 43 z 61 · około 9 minut
Interfejsy i polimorfizm
Wylicz zniżki: zdefiniuj kontrakt interfejsem i traktuj różne klasy przez niego tak samo.
Czego się nauczysz
- Napisać interfejs
- Zaimplementować go w kilku klasach
- Użyć jednej listy dla różnych typów
Zniżki
Klienci pytają o zniżki: bilet studencki jest o 20% tańszy, a bilet na seans poranny o $3. Każda zniżka ma nazwę i wylicza cenę, ale każda robi to inaczej, więc kasa pisze interfejs Offer z name() i apply(cents) oraz domyślną metodą describe(cents), którą każda zniżka dostaje za darmo. StudentOffer i MatineeOffer go implementują. Klient wpisuje zniżki aż do done, trafiają one do jednej List<Offer>, a jedna pętla wypisuje o.describe(priceCents) dla każdej: Java uruchamia własne apply() każdego obiektu.
Kontrakty
Interfejs wymienia metody, które klasa obiecuje dostarczyć, bez mówienia, jak:
interface Shape { double area(); String name(); }
class Circle implements Shape musi dostarczyć obie. Wtedy każdy kod, który działa z Shape, działa z każdą klasą, która go implementuje. To jest polimorfizm. Klasa może implementować wiele interfejsów, ale rozszerzać tylko jedną klasę.
Jedna lista, wiele kształtów
import java.util.List;
interface Shape {
double area();
default String describe() {
return getClass().getSimpleName() + " with area " + String.format("%.2f", area());
}
}
class Square implements Shape {
private final double side;
Square(double side) { this.side = side; }
public double area() { return side * side; }
}
class Circle implements Shape {
private final double r;
Circle(double r) { this.r = r; }
public double area() { return Math.PI * r * r; }
}
public class Main {
public static void main(String[] args) {
List<Shape> shapes = List.of(new Square(3), new Circle(1));
double total = 0;
for (Shape s : shapes) {
System.out.println(s.describe());
total += s.area();
}
System.out.printf("Total: %.2f%n", total);
}
}Wyjście
Square with area 9.00
Circle with area 3.14
Total: 12.14Wskazówka
Metody interfejsu są publiczne, więc metody, które je implementują, też muszą być publiczne. Metoda default daje każdej implementacji gotową wersję.
Metody domyślne
Metoda default w interfejsie ma ciało napisane za pomocą innych metod interfejsu. Każda klasa implementująca interfejs dostaje ją taką, jaka jest, a klasa, która chce czegoś innego, może ją nadpisać jak każdą inną metodę.
Powitanie dla wszystkich i jedno inne
import java.util.List;
interface Greeter {
String name();
default String greet() {
return "Hello from " + name();
}
}
class Usher implements Greeter {
public String name() {
return "the usher";
}
}
class Robot implements Greeter {
public String name() {
return "the robot";
}
@Override
public String greet() {
return "BEEP. " + name().toUpperCase();
}
}
public class Main {
public static void main(String[] args) {
for (Greeter g : List.of(new Usher(), new Robot())) {
System.out.println(g.greet());
}
}
}Wyjście
Hello from the usher
BEEP. THE ROBOTTeraz spróbuj sam
Ta lekcja jest darmowa w Codiqo i ma 8 pytań o to, co właśnie przeczytałeś. Programowania uczy się, programując, więc kończy się krótkim programem, który piszesz sam, a my od razu go uruchamiamy i sprawdzamy.