public interface Ocenitelny { public int getCena(); } public interface Vazitelny { public int getVaha(); }
Výčtový typ definuje množinu konstant. V Javě enum dovoluje použití atributů a metod. Všechny výčtové typy implicitně dědí z java.lang.Enum (proto ani nemohou dědit z ničeho jiného).
Konstruktor musí být privátní. Slouží k vytváření definovaných konstant. Konstruktor nemůžeme zavolat explicitně.
Enum v Javě navíc poskytuje speciální metody. Například statická metoda values vrací pole všech hodnot daného výčtového typu. Toto se hodí pro použití ve for-each cyklu.
public enum Color { RED("červená"),GREEN("zelená"),BLUE("modrá"); private final String localizedValue; private Color(String localizedValue) { this.localizedValue = localizedValue; } public String getLocalizedValue() { return localizedValue; } @Override public String toString() { return localizedValue; } public static void main(String[] args) { for(Color c : Color.values()) { System.out.print(c + ","); } System.out.println(); } }
public class Main { public int f(int x) { //2,3,4,5 if (x <= 0) { return 0; } int y = x + f(x - 1); //6,7,8 return y; } public static void main(String[] args) { Main main = new Main(); //1 int y = main.f(3); //9 System.out.println(y); } }
public class Main { public int f2(int x) { int y = 0; int i = 1; while (i <= x) { //2,3,4 y += i; i++; } //5 return y; } public static void main(String[] args) { Main main = new Main(); //1 int y = main.f2(3); //6 System.out.println(y); } }
class Vector { final double x, y; private static Vector testVector = null; Vector(double x, double y) { this.x = x; this.y = y; // stav B } double getX() { return x; } double getY() { return y; } static Vector testVector() { // stav A if (testVector == null) testVector = new Vector(1.0, 0.0); return testVector; } Vector funcionMagica() { double[] a = {1.0, 0.5, -1.0, -1.0}; Vector v = this; for (double d : a) v = new Vector(Math.sin(Math.PI * d), Math.cos(Math.PI * d)); return v; } public static void main(String[] args) { Vector v = Vector.testVector(); double k = v.getY() / v.getX(); Vector v2 = v.funcionMagica(); // stav C } }