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.