Reference to an instance method of a particular object
Posted
by
Andrey
on Stack Overflow
See other posts from Stack Overflow
or by Andrey
Published on 2014-08-20T16:08:36Z
Indexed on
2014/08/20
16:20 UTC
Read the original article
Hit count: 166
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,
© Stack Overflow or respective owner