For practice purposes, I want to achieve the following.
Have simple Interface
Simple class that implements that interface
Make two instances of the class
Store them in collection (ArrayList in this example)
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With