I saw this Java snippet in the book Spring in Action, but I'm not familiar with the language construct.
new RowMapper() {
public Object mapRow() throws SQLException, DataAccessException {
Motorist motorist = new Motorist();
motorist.setId(rs.getInt(1));
motorist.setEmail(rs.getString(2));
motorist.setPassword(rs.getString(3));
motorist.setFirstName(rs.getString(4));
motorist.setLastName(rs.getString(5));
return motorist;
}
}
According the Spring documentation, RowMapper is an interface. It looks to me like an anonymous class definition based on the RowMapper interface. The new
keyword is a little confusing, making me wonder if this also creates one instance of the anonymous class. I would guess yes, because if the class has no name, how will you ever create an instance after the line that defines it?
Can anyone confirm my guesses that:
How to implement interface in anonymous class in C#? No, anonymous types cannot implement an interface. We need to create your own type. Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.
Anonymous class usually extends a subclass or implement an interface Functional Interface is simply an interface that has exactly one abstract method. For example, the interface Animal is a Functional Interface. You can annotate functional interfaces with @FunctionalInterface
Types of anonymous inner class : Based on declaration and behavior, there are 3 types of anonymous Inner classes: Anonymous Inner class that extends a class : We can have an anonymous inner class that extends a class.For example,we know that we can create a thread by extending a Thread class.
Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope: An anonymous class has access to the members of its enclosing class.
This is an anonymous class definition based on the RowMapper interface
That's precisely what it is.
It creates a single instance of that class?
Yep. That's correct.
That code is implementing the interface in an anonymous way.
The syntax would be similar to:
Runnable runnable = new Runnable() {
public void run() {
}
};
Note the semicolon at the end of the declaration. Here the runnable object, though holds the reference to the Runnable interface actually contains the implemented object. That's runtime polymorphism for you!
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