-1
package example;

import java.util.ArrayList;
import java.util.Iterator;

public class anaBolum {
    public static void main(String[] args) {
        ArrayList<IMeyveler> list = new ArrayList<>();
        list.add(new Muz());
        list.add(new Elma());

        Iterator it = list.iterator();
        while(it.hasNext()){
            it.next().fiyat() //compile error
        }
    }
}

I was use list.iterator() to access the list elements. But I can't access this method fiyat() in the iterator because I get compile error.

kibar
  • 801
  • 3
  • 17
  • 36

4 Answers4

0

I assume you are getting some compile time error. If so You need to change the iterator declaration to Iterator<IMeyveler> it = list.iterator();

Other wise the iterator will not know the type of objects handled by it.

public class anaBolum {
    public static void main(String[] args) {
        IMeyveler muz = new Muz();
        muz.fiyat();// Work

        ArrayList<IMeyveler> list = new ArrayList<>();
        list.add(new Muz());
        list.add(new Elma());

        Iterator<IMeyveler> it = list.iterator();
        while(it.hasNext()){
            System.out.println(it.next().fiyat());
        }
    }
}
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
0

You need to do like this

    while(it.hasNext()){
        Object obj = it.next() ;
        if( obj instanceof Muz ) {
          Muz muz = (Muz) obj ;
          muz.fiyat();
        }
    } 
vels4j
  • 11,026
  • 5
  • 39
  • 57
0

Your CodeCompletion does not show up, because .next() returns an object and not IMeyveler. You will either have to cast, or iterate differently.

    System.out.println(((IMeyveler)it.next()).fiyat());
cppanda
  • 1,185
  • 1
  • 14
  • 29
0

Try this one:

package javaaa;

import java.util.ArrayList;
import java.util.Iterator;

public class anaBolum {
    public static void main(String[] args) {
        IMeyveler muz = new Muz();
        muz.fiyat();// Work

        ArrayList<IMeyveler> list = new ArrayList<>();
        list.add(new Muz());
        list.add(new Elma());

        for(IMeyveler fruit : list)
        {
            if(fruit instanceof Muz)
            {
                System.out.println(fruit.fiyat());
            }
        }  
    }
}
vtokmak
  • 1,492
  • 6
  • 33
  • 66