Reference to an instance method of a particular object
- by Andrey
In the following code, if i try to pass method reference using the class name, works. But passing the reference variable compiler gives an error, i do not understand why?
public class User {
    private String name;
    public User(String name) {
        this.name = name;
    }
    public void printName() {
        System.out.println(name);
    }    
}
public class Main {
    public static void main(String[] args) {
        User u1 = new User("AAA");
        User u2 = new User("BBB");
        User u3 = new User("ZZZ");
        List<User> userList = Arrays.asList(u1, u2, u3);        
        userList.forEach(User::printName); // works
        userList.forEach(u1::printName); // compile error
    }
}
Thanks,