Java: Interface - wiem co to jest

W zasadzie, to wystarczy prześledzić to, co robi ten kod:

import java.util.ArrayList;
import java.util.List;

public class Suma {

    private static List<X> tab = new ArrayList<>();

    public static void main(String[] args) {
        tab.add(new X1());
        tab.add(new X2());
        tab.add(new X3());

        someMethod();
    }

    static void someMethod() {
        for(X x: tab) {
            x.doSomething();
            x.yes();
        }
    }

}

public interface X {
    void doSomething();
    void yes();
}

public class X1 implements X {

    public void doSomething(){
        System.out.println("X1");
    }

    public void yes(){
        System.out.println("yes1");
    }

    public void no(){
        System.out.println("no1");
    }
}

public class X2 implements X {

    public void doSomething(){
        System.out.println("X2");
    }

    public void tak(){
        System.out.println("yes2");
    }

}

public class X3 implements X {

    public void doSomething(){
        System.out.println("X3");
    }

    public void yes(){
        System.out.println("yes3");
    }

}

Albo to wkleić do IDE i zastanowić się, jak to możliwe, że ta sama metoda wywołana 3 razy, daje różne efekty :)

No dobra, żeby było łatwiej i jaśniej to tutaj jest inny przykład:

import java.util.ArrayList;
import java.util.List;

public class Test {

    private static List<Figure> list = new ArrayList<>();

    public static void main(String[] args) {
        list.add(new Circle(10d));
        list.add(new Rectangle(10.3d, 2d));

        for (Figure figure : list) {
            System.out.format("This is %s field: %f%n", figure.getName(), figure.calcField());
        }
    }
}

public interface Figure {
    Double calcField();
    String getName();
}
public class Circle implements Figure {

    Double radius;
    String name = "Circle";

    Koło(Double radius) {
        this.radius = radius;
    }

    @Override
    public Double calcField() {
        return Math.PI*radius*radius;
    }

    @Override
    public String getName() {
        return name;
    }
}
public class Rectangle implements Figure {

    Double a,b;
    String name = "Rectangle";

    Rectangle(Double a, Double b){
        this.a=a;
        this.b=b;
    }

    @Override
    public Double calcField() {
        return a*b;
    }

    @Override
    public String getName() {
        return name;
    }
}

Jeśli ktoś będzie w stanie powiedzieć jak to możliwe, że raz liczy pole koła, a raz prostokąta, to śmiało już może o sobie mówić Upper Junior, bo jest trudne i nie wystarczy tego wklepać na pamięć :)



Bardzo mnie interesuje co o tym sądzisz, dlatego byłoby mi miło, jeśli byś napisał w komentarzu coś o tym, np. co o tym sądzisz czy coś... :)

Komentarze

Popularne posty z tego bloga

IntelliJ: zmiana rozmiaru czcionki scrollem

ThunderBird: jak zrobić professional stopkę