Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing method on object while iterating [duplicate]

Tags:

java

For practice purposes, I want to achieve the following.

  1. Have simple Interface

  2. Simple class that implements that interface

  3. Make two instances of the class

  4. Store them in collection (ArrayList in this example)

  5. Iterate over the collection calling the method on the class

Interface:

public interface MyInterface {
     void sayHello();
}

Class:

public class Person implements MyInterface{
    private String name;

    public Person(String nameValue) {
        name = nameValue;
    }

    @Override
    public void sayHello() {
        System.out.println(name);
    }
}

Main:

public class DemoApplication {

    public static void main(String[] args) {
        ArrayList<MyInterface> personHolder = new ArrayList();
        MyInterface me = new Person("Myself");
        MyInterface daughter = new Person("Daughter");
        personHolder.add(me);
        personHolder.add(daughter);

        greeter(personHolder);

    }

    static void greeter(ArrayList persons){

        persons.forEach((person -> {

        }));        
    }
}

Now inside the greeter method in the the loop, I was expecting to simply call:

person.sayHello()

But when I inspect the person, I do not see the class method. After some playing around, this piece of code that casts Person seems to work:

((Person) person).sayHello();

Where is my method gone? Why Do I have to cast in order to get it? My background is Javascript, and I kinda expected to have it right there.

like image 587
Wexoni Avatar asked Jul 10 '26 19:07

Wexoni


2 Answers

You are using a raw type:

static void greeter(ArrayList persons)

so you can only access methods of the Object class inside persons.forEach.

You should change it to:

static void greeter(List<MyInterface> persons)

Note that I used the List interface instead of the ArrayList implementation, since it's considered better practice to program to interfaces.

like image 187
Eran Avatar answered Jul 13 '26 10:07

Eran


change the greeter function and add a generic MyInterface:

static void greeter(ArrayList<MyInterface> persons) {
...
}

Otherwise Java won't knows nothing about what's stored in the array list and thinks that its an Object (because everything is an object). Obviously object doesn't have sayHello method that's why you had to do casting.

Another thing, more a code style - just an advice:

In java we usually work against interface whenever possible, so prefer interface List<MyInterface> over concrete implementation ArrayList<MyInterface> both in "greeter" implementation and in method.

like image 28
Mark Bramnik Avatar answered Jul 13 '26 11:07

Mark Bramnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!