2014-02-21 2 views
0

У меня есть класс, который содержит объект, который может существовать только внутри класса. (То есть, объект никогда не будет использоваться вне класса.) Таким образом, я должен захотеть, чтобы объект имел доступ к защищенным методам класса.Отношение HAS-A с наследованием в Java

Поскольку класс создает экземпляр объекта, я не хочу, чтобы объект расширял класс, потому что это создало бы экземпляр объекта класса, который бы создавал экземпляр объекта, так далее и т. Д. До конца времени.

Итак, есть ли способ позволить объекту иметь доступ к защищенным методам класса?

Извините, если это простой вопрос для ответа, но в этой конкретной ситуации очень сложно.

ответ

2

Если класс используется только внутри другого класса, сделать его внутренний класс. См. Этот пример:

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 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(); 
    } 
} 
+0

Это делает то, что мне нужно. Благодарю. – user3337629

+0

, пожалуйста, примите, нажав «check». –

0

Как таковой, я хочу, чтобы объект, чтобы иметь доступ к защищенных методов класса в ,

Изучите создание внутренних классов. Объекты внутренних классов могут обращаться к методам охватывающего класса. Посмотрите на official Java tutorials on nested classes.

SSCCE:

public class Outer{ 
    private int value = 99; 

    public Outer(){ // Creating an object of Outer class 
     new Inner(); // creates an object of Inner class 
    } 

    private int getEnclosedValue(){ // Accessor for getting the int value 
     return value; 
    } 

    public class Inner{ 
     public Inner(){ // Constructor for Inner class calls getEnclosedValue() 
      System.out.println(getEnclosedValue()); // of the Outer class 
     } 
    } 

    public static void main(String[] args){ 
     new Outer(); 
    } 
} 
+0

Другой путь тоже прав. Закрывающий класс имеет доступ к членам, даже частным, из его внутренних классов. –

+0

@JBNizet Я никогда не рассматривал это. Спасибо за исправление –

Смежные вопросы