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:
this is an anonymous class definition based on the RowMapper interface, and
it creates a single instance of that 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!
Your guesses are entirely correct. An anonymous class definition may be based on either a non-final class or on an interface, and you must implement all abstract (or interface) methods. The only available syntax for declaring anonymous classes is new, which also has the effect of instantiating exactly one instance of the anonymous class (in the course of the program, though, many instances of the same anonymous class could be created, if this code is executed several times).
Interface tells what methods the built class instance should have or if thy are label interfaces, then what kind of behavior to associate with it.
Anonymous classes are classes that basically while instantiating a class instance thy are also extending it with custom code. So if you are instantiating a interface, then you must write all the methods described with that interface, and as long as you do at least that much, then compiler will be happy. This is what is done here.
IS this is an anonymous class definition based on the RowMapper interface?
Yes. As you can see mapRow() function has been written. And if you debug the code you can see, that is not a class of an instance of interface, but class that extends interface. In case of abstract class or just class, it would be same - extended. So if class is final you cant write anonymous class for it.
Does it create a single instance of that class?
Well, it extends it and makes an instance of it. It will be single instance and any sequent call to it would result in a different class. If you debug the code, then you can even see different class names dynamically associated with it.
Solely from the code above and without knowing about RowMapper, all you can assume is that a new anonymous class based on RowMapper (which may be an interface or a class) is instantiated.
Declaring Anonymous class and in below example it creates two instances .
public class Multithread {
void test(){
new Runnable() {
#Override
public void run() {
System.out.println("1");
}
}.run();
new Runnable() {
#Override
public void run() {
System.out.println("11");
}
}.run();}
public static void main(String[] args) {
new Multithread().test();
}
}
Related
Suppose I have these classes:
public class ChildClass extends ParentClass
{
// some class definition here
}
public abstract class ParentClass
{
public static void printClass()
{
// get the class that extends this one (and for example, print it)
}
// some class definition here
}
Lets say when calling ParentClass.printClass() I want to print the name of the class (like doing System.out.println(ParentClass.class)). When then extending ParentClass (for example like in ChildClass) and calling ChildClass.printClass(), I want it to print the name of the extending class (like doing System.out.println(ChildClass.class)). Is this somehow possible?
I've found a way to get the class from inside a static method by using MethodHandles.lookup().lookupClass(), but when using it inside of ParentClass.printClass and extending ParentClass, then calling printClass on the extending Class, I always get the class of ParentClass.
static methods are best thought of as living entirely outside of the class itself. The reason they do show up in classes is because of the design of java (the language) itself: Types aren't just types with a hierarchy, they also serve as the primary vehicle for java's namespacing system.
Types live in packages, packages are the top level namespace concept for types. So how do you refer to a method? There's only one way: Via the type system. Hence, static methods do have to be placed inside a type. But that's about where it ends.
They do not inherit, at all. When you write:
ChildClass.lookupClass()
The compiler just figures out: Right, well, you are clearly referring to the lookupClass() method in ParentClass so that is what I will compile. You can see this in action yourself by running javap -c -p MyExample. The same principle applies to non-static methods, even.
For instance methods, the runtime undoes this maneuvre: Whenever you invoke a method on any object, the runtime system will always perform dynamic dispatch; you can't opt out of this. You may write:
AbstractList<String> list = new ArrayList<String>();
list.sort(someComparator);
and you can use javap to verify that this will end up writing into the class file that the method AbstractList::sort is invoked. But, at runtime the JVM will always check what list is actually pointing at - it's an instance of ArrayList, not AbstractList (that's obvious: AbstractList is abstract; no object can ever be directly instantiated as `new AbstractList). If ArrayList has its own take on the sort method, then that will be called.
The key takeaway of all that is: Static methods do not inherit, therefore, this dynamic dispatch system is not available to them, therefore, what you want cannot be done in that fashion.
So what to do?
It feels like what you're doing is attempting to associate a hierarchy to properties that apply to the class itself. In other words, that you want there to be a hierarchical relationship between the notion of 'ParentClass's lookupClass method and ChildClass's lookupClass method - lookupClass is not a thing you ask an instance of ChildClass or ParentClass - you ask it at the notion of the these types themselves.
If you think about it for a moment, constructors are the same way. You don't 'ask' an instance of ArrayList for a new arraylist. You ask ArrayList, the concept. Both 'do not really do' inheritance and cannot be abstracted into a type hierarchy.
This is where factory classes come in.
Factory classes as a concept are just 'hierarchicalizing' staticness, by removing static from it: Create a sibling type to your class hierarchy (ParentClassFactory for example):
abstract class ParentClassFactory {
abstract ParentClass create();
abstract void printClass();
}
and then, in tandem with writing ChildClass, you also write ChildClassFactory. Generally factories have just one instance - you may want to employ the singleton pattern for this. Now you can do it just fine:
class ChildClassFactory extends ParentClassFactory {
private static final ChildClassFactory INSTANCE = new ChildClassFactory();
public static ChildClassFactory instance() { return INSTANCE; }
public ParentClass create() { return new ChildClass(); }
public void printClass() { System.out.println(ChildClass.class); }
}
// elsewhere:
// actually gets the ChildClassFactory singleton:
ParentClassFactory factory = ....;
factory.printClass(); // will print ChildClass!
Quoting #RealSkeptic:
Static methods are not inherited. The fact that you can call ChildClass.printClass() is just syntactic sugar. It actually always calls ParentClass.printClass(). So you can't do something like that with a static method, only an inheritable non-static one.
Is it important to save all class code as individual .java files like following way?
Outer.java,
Inner.java,
Test.java
Or can I make a single java file as Test.java. Please explain anonymous class, how can we create anonymous class in java, and what is the advantage/disadvantage over normal class?
class Outer {
private int data = 50;
class Inner {
void msg() {
System.out.println("Data is: " + data);
}
}
}
class Test {
public static void main(String args[]) {
Outer obj = new Outer();
Outer.Inner in = obj.new Inner();
in.msg();
}
}
See the Code Conventions for the Java programming language:
Each Java source file contains a single public class or interface.
When private classes and interfaces are associated with a public
class, you can put them in the same source file as the public class.
The public class should be the first class or interface in the file.
I think this should answer your question. As I stated in my comment, it's not recommended to write a file that contains several unrelated classes. However, if you have an associated classes with that one public class you have in the file, you can place them in the same source file.
An anonymous class in Java is a class not given a name and is both declared and instantiated in a single statement. You should consider using an anonymous class whenever you need to create a class that will be instantiated only once.
Although an anonymous class can be complex, the syntax of anonymous class declarations makes them most suitable for small classes that have just a few simple methods.
An anonymous class must always implement an interface or extend an abstract class. However, you don’t use the extends or implements keyword to create an anonymous class. Instead, you use the following syntax to declare and instantiate an anonymous class:
new interface-or-class-name() { class-body }
Within the class body, you must provide an implementation for each abstract method defined by the interface or abstract class. Here’s an example that implements an interface named runnable, which defines a single method named run:
runnable r = new runnable()
{
public void run()
{
//code for the run method goes here
}
};
Here are a few other important facts concerning anonymous classes:
An anonymous class cannot have a constructor. Thus, you cannot pass parameters to an anonymous class when you instantiate it.
An anonymous class can access any variables visible to the block within which the anonymous class is declared, including local variables.
An anonymous class can also access methods of the class that contains it.
yes you can do this , but it should be in small programming,
while in big application you have to make class individual, Java strongly recommended that to make class different file, but it depends on you to do so.
Can someone explain this line of code for me?
SomeAbstractClass variable = new SomeAbstractClass() { };
This properly instantiaties and stores the abstract instance in the variable. What is happening? An anonymous class that extends the abstract class, maybe? Any keywords I can use to look up information about this? (the abstract class also happens to be generic if that has any relevance)
The line above is creating an anonymous subclass of SomeAbstractClass, which will not be abstract. Of course, this will work only if the base class has no abstract methods to implement.
Actually, I cannot visualize an useful instance (besides "documentation" features, see the comment below) of the line above, unless you are implementing and/or overriding methods between curly braces. That is a quite common technique if the base class/interface happens to have few methods to implement and the implementation is simple. You can even refer to the final variables of the surrounding method and parameters, thus making a closure.
You are creating an anonymous class which is a subclass of your abstract class. Like was pointed out in comments, you are looking at an anonymous extends.
Something like follows would work if you had abstract methods to implement:
MyAbstractClass someObjectOfThatClass = new MyAbstractClass(){
#Override
public void someAbstractMethod(){
}
}
You can do the same with interfaces as they can also contain abstract methods. A practical example would be adding an ActionListener to a JButton:
myJButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
// code
}
});
Java gives you the ability to create anonymous subclasses inline. You often see this in the context of anonymous inner classes with Swing event handling, but there are many other applications as well.
In your example, you are creating a class that extends SomeAbstractClass anonymously and assigning it to a SomeAbstractClass reference. It would be just as if you created a separate class like this
public class SomeConcreteClass extends SomeAbstractClass {
}
and later did this
SomeAbstractClass variable = new SomeConcreteClass();
As noted by #Stefano, your approach only works if your anonymous concrete class has no abstract methods, which would be true because SomeAbstractClass has no abstract methods.
I am trying to use template design pattern so I use abstract class to define my algorithm like this:
abstract class MyTemplate
{
public void execute()
{
//... do something
doSomething();
}
public abstract void doSomethig();
}
In my code I will create an instanceof MyTemplate everytime like this:
MyTemplate cleanUp = new MyTemplate()
{
public void doSomething()
{
// execute cleanup
}
}
cleanUp.execute();
Is creating a object out of abstract class expensive for JVM?
Thanks,
Sean Nguyen
No, the compiler generates an anonymous inner class at, er, compile time. Instantiating an object of this class is no more expensive than for any other class.
You're not really creating an abstract class instance. You're creating an instance of a concrete class which happens to have no name in your code, created by the Java compiler.
The JVM doesn't really know or care about that - so it's only as expensive as creating an instance of any other class which happens to be a subclass of an abstract class. So don't sweat it :)
Internally, the JVM implements this behavior by having the Java compiler create a new .class file for the anonymous class you created on-the-fly, then instantiating a new object of that type. Consequently, there is a (very small) one-time cost for loading the new class into the JVM, but from that point forward the cost of creating the new object is the same as the cost of creating any other object.
In other words, no, there is not a large inefficiency introduced by this code.
Though i have often come across,i dont understand this way of writing code:
Runnable r=new Runnable() {//<----- (braces start here?)
public void run() {
System.out.println("Hello");
}
}; // ?
What is this?
Please explain very clearly.
That's an anonymous inner class. It's creating an implementation of the Runnable interface using code within the braces. As well as implementing interfaces, you can extend other classes. The nice aspects are that you can do this without explicitly creating a separate class, and you can also refer to final local variables (including parameters) within the body of the anonymous inner class.
See the Java tutorial for more details, or just search for "anonymous inner class" for loads of related pages.
As mentioned by others, what is being created here is an anonymous inner class. Specifically, the person who wrote the code is saying:
Instead of an instance of the Runnable class, I want to create a subclass that overrides the "run()" method and create an instance of that. Its not worth my time to create a named subclass, since I'm only going to create this one instance. Instead, just override the method and return the subclass instance I need.
That's an anonymous class declaration - basically, a class that implements the Runnable interface, declared and instantiated inline as an anonymous nested class.
Note that you can also declare anonymous subclasses the same way:
Object o = new Object(){
public String toString(){ return "boo!" };
}
Also note that you can use variables of the enclosing method inside the anonymous class code, but only if the variables are final (because the anonymous class actually gets a copy of the variable).
I would start with these http://www.google.co.uk/search?q=anonymous+classes+tutorial 23 million results.
Basically, it allows you to define an implementation or a subclass without having to create a fully formed class defintiions.
EDIT: For your own interest, see if you can figure out what this does.
Map<String, String> map = new LinkedHashMap<String, String>() {{ // two brackets
put("a", "aye");
put("b", "bee");
put("c", "see");
put("d", "dee");
put("e", "ee");
put("f", "eff");
}};
It's so called 'anonymous class'.
You can do this:
class MyRunnable implements Runnable{
public void run() {
System.out.println("Hello");
}
}
Then:
Runnable r = new MyRunnable();
And achieve the same thing. However, the MyRunnable class that you created is never needed in any other part of your code. So creating a named class is not necessary. The code that you wrote on the other hand is creating an anonymous inner class such that the implementation of the class is precisely where it is needed. It will not be accessible rom anywhere else in the code but that is the idea, you do not need it anywhere else.