java:anon_inner_classes

This is an old revision of the document!


A PCRE internal error occured. This might be caused by a faulty plugin

====== Ανώνυμές εμφωλευμένες κλάσεις ====== Οι ανώνυμές εμφωλευμένες κλάσεις επιτρέπουν τον ταυτόχρονο ορισμό της υλοποίησης της κλάσης μαζί με την δημιουργία ενός αντικειμένου της κλάσης αυτής, σε μία εντολή. Οι κλάσεις αυτές χρησιμοποιούνται στην συγγραφή προγραμμάτων και πρέπει **α)** να υλοποιούν ένα υφιστάμενο interface ή **β)** να επεκτείνουν μία υφιστάμενη κλάση. Δείτε το παράδειγμα που παρουσιάστηκε στις μη στατικές εμφωλευμένες κλάσεις αλλαγμένο, ώστε να χρησιμοποιεί ανώνυμες κλάσεις <code java DataStructure.java> public class DataStructure { // Create an array private final static int SIZE = 15; private int[] arrayOfInts = new int[SIZE]; public DataStructure() { // fill the array with ascending integer values for (int i = 0; i < SIZE; i++) { arrayOfInts[i] = i; } } interface DataStructureIterator extends java.util.Iterator<Integer> { } public void printEven() { // Print out values of even indices of the array //DataStructureIterator iterator = this.new EvenIterator(); DataStructureIterator iterator = new DataStructureIterator() { // Start stepping through the array from the beginning private int nextIndex = 0; public boolean hasNext() { // Check if the current element is the last in the array return (nextIndex <= SIZE - 1); } public Integer next() { // Record a value of an even index of the array Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]); // Get the next even element nextIndex += 2; return retValue; } public void remove() { } }; while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } System.out.println(); } public static void main(String s[]) { DataStructure ds = new DataStructure(); ds.printEven(); } } </code>

java/anon_inner_classes.1430409323.txt.gz · Last modified: 2016/02/26 11:15 (external edit)