java:inner_classes

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
java:inner_classes [2017/02/06 13:14]
gthanos
java:inner_classes [2021/04/12 04:31]
Line 1: Line 1:
-====== Μη στατικές εμφωλευμένες κλάσεις ====== 
  
-Οι μη στατικές εμφωλευμένες κλάσεις ή εσωτερικές κλάσεις (inner classes) αποτελούν την γενικότερη περίπτωση εμφώλευσης μίας κλάσης μέσα σε μία άλλη κλάση. Δείτε το παρακάτω παράδειγμα απεικόνισης των ζυγών στοιχείων ενός πίνακα 15 στοιχείων με χρήση μίας εσωτερικής κλάσης η οποία υλοποιεί το interface [[https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html|Iterator]]: 
- 
-<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; 
-    } 
-  } 
-   
-  public void printEven() { 
-     
-    // Print out values of even indices of the array 
-    DataStructureIterator iterator = this.new EvenIterator(); 
-    while (iterator.hasNext()) { 
-      System.out.print(iterator.next() + " "); 
-    } 
-    System.out.println(); 
-  } 
-   
-  interface DataStructureIterator extends java.util.Iterator<Integer> { }  
- 
-  // Inner class implements the DataStructureIterator interface, 
-  // which extends the Iterator<Integer> interface 
-   
-  private class EvenIterator implements 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() { } 
-  } 
-   
-  public static void main(String s[]) { 
-     
-    // Fill the array with integer values and print out only 
-    // values of even indices 
-    DataStructure ds = new DataStructure(); 
-    ds.printEven(); 
-  } 
-} 
-</code> 
- 
-<WRAP todo center 80% round> Σε αναλογία, δημιουργήστε την εσωτερική κλάση **OddIterator** και τη μέθοδο **printOdd()** για την εκτύπωση των μονών αριθμών του πίνακα.  
-</WRAP> 
- 
- 
-|Προηγούμενο: [[ :java:nested_classes| Εμφωλευμένες κλάσεις  ]] |  [[:toc|Περιέχόμενα]]  |Επόμενο: [[ :java:inner_class_objects | Δημιουργία αντικειμένων της εσωτερικής κλάσης ]]| 
java/inner_classes.txt · Last modified: 2021/04/12 04:31 (external edit)