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.
Related
An anonymous class is something like this:
SenseOfLife _42 = new SenseOfLife() {
public int eval() {
return 42;
}
};
I didn't understand why such an anonymous class can have an unbounded number of instances (this is a proposition).
While I'm defining this anonymous class it creates automatically an instance and assigns it to the variable _42. So I have only one instance and cannot create a new instance.
You could create multiple instances by:
Executing the same block of code more than once.
Cloning an instance of an anonymous class.
If the interface extends Cloneable the class could technically be cloned.
Reflection could get a new instance.
If the same new SenseOfLife() constructor is called in a loop that constructor will get compiled down to one class that is instantiated multiple times.
I haven't tried it, but most likely you can create other instances using reflection, i.e., instance.getClass().newInstance().
I am refactoring a class with a public facing interface and thinking about the usage led me to ask:
What is the difference between declaring the following within some larger class (as an instance variable):
private final OnClickListener mButtonOnClickListener = new OnClickListener() {
#Override
public void onClick(View view) {
//some codes
}
};
vs declaring as an anonymous inner class as follows (on the fly):
private void someFunctionInClass() {
someOtherFunctionThatTakesAnOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//some codes
}
});
}
More specifically, is the former still considered an anonymous inner class? I read in this answer that an anonymous inner class
is one that is created AND defined within the body of another class' method
The first example I gave is created and defined within the body of another class but not within another class' method as the second one is. Is it still an anonymous inner class? Furthermore, what is the accepted practice for one vs. another? Is it more efficient to declare (what I think is still) an anonymous inner class as an instance variable because new objects don't need to be recreated?
Both of these are anonymous classes. Other than scope there is not much difference. But below is a link that can be used in deciding which to use from
Local class:
Anonymous class:
Nested class:
Lambda expression:
http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html
I hope it helps.
Those are both anonymous classes. In the first one, you can reuse it, but both are just objects that are created. An anonymous class is necessarily an inner class, and can access any fields of the enclosing class.
I think you may be getting anonymous classes confused with inner classes and static nested classes, which have distinct differences.
Both are anonymous classes. Taking the example of a listener, if you intend to use the same listener for two components you can have an instance variable for that else you can directly attach it to the component. So it depends on the requirement.
But mostly its a sort-of one-time use, that is, you avoid creating instance for that. If you intend to reuse it, its better you create a separate class for that.
Both are anonymous classes. An anonymous class is a constructor (new ClassName()) followed by a class body ({...}).
In your examples, in both cases you have created anonymous inner class. That it "new OnClickListener() {" I think it does not have overhead since its getting resolved at compile time. People use it all the time.
Here is a factory "inner class?" from the Java Jung graph package:
Factory<Graph<String, Integer>> graphFactory = new Factory<Graph<String, Integer>>()
{
public Graph<String, Integer> create()
{
return new SparseMultigraph<String, Integer>();
}
};
What I want to know is what programming language concept is the above? Especially what is this concept in Java? Is the above an inner class? It is clearly not a method. It seems odd to me because it constructs a Factory object and then has braces with a semicolon at the end with a method to create a graph.
It is an anonyous inner class. The above code creates a subclass of the Factory class (or a class implementing the Factory interface), overrides its create() method, calls its constructor, and assigns the result to the graphFactory variable.
It is an anonymous inner class.
It's an anonymous inner class concept.In layman terms,it can also be called an unnamed class.There is always a debate on the use of such classes against inheritance.Usually,if there is a one time usage requirement of a child class,then anonymous classes are more handy than inherited classes.
As per the post it seems that you are aware that it is the concept of anonymous class in java that you are talking about.
Now since you are questioning y this :
The answer is that , as the name implies the class has no name, hence in a single step
class declaration
the creation of an instance of the class
is complete. Due to this reason use of anonymous class save time and effort for creating a .java file. :)
As a rule anonymous class must implement all the abstract methods in the super class or the interface and should use all the default constructor of the super class.
I was going through some code and I saw this:
public class A {
public A(SomeObject obj) {
//Do something
}
//Some stuff
public static class B {
//Some other stuff
}
}
I was wondering since even the inner class is public why have it as nested and not a separate class?
Also, can I do this here: new A.B(SomeObject) ? I feel this defeats the purpose of a static class but I saw this implementation as well so wanted to know.
I was wondering since even the inner class is public why have it as nested and not a separate class?
That's really a matter to ask whoever wrote the class. It can allow the outer class to act as a "mini-namespace" though - if the nested class is only useful in the context of the outer class, it seems reasonable. It indicates deliberate tight coupling between the two classes. I most often see this in the context of the builder pattern:
Foo foo = new Foo.Builder().setBar(10).build();
Here it makes sense to me to have Foo.Builder nested within Foo rather than as a peer class which would presumably be called FooBuilder.
Note that it also gives some visibility differences compared with just unrelated classes.
Also, can I do this here: new A.B(SomeObject) ?
No, because B doesn't have a constructor with a SomeObject parameter - only A does (in the example you've given).
I feel this defeats the purpose of a static class
You should try to work out exactly what you deem the purpose of a static class to be, and in what way this defeats that purpose. Currently that's too vague a statement to be realistically discussed.
You would have an inner class like this so
you can keep an class which only exists to support the outer class encapsulated.
you want to be able to access private members of the outer class or other nested classes.
you want a nested class with static fields (a weak reason I know ;)
you have a class with a very generic name like Lock or Sync which you wouldn't want to be mixed with other classes of the same name used by classes in the same package.
can I do this here: new A.B(SomeObject) ?
You can.
I feel this defeats the purpose of a static class
It takes getting used to but once you start you may have trouble not turning your entire program into one file.java ;)
1. A static inner class is known as Top-Level Class.
2. This static class has direct access to the Its Outer class Static method and variables.
3. You will need to initialize the static Inner class in this way from Outside...
A a = new A();
A.B b = new A.B();
4. new A.B(SomeObject) won't work... because you don't have a constructor with SomeObject as parameter...
5. But when the Inner class is Non-static, then it have implicit reference to the Outer class.
6. The outer and inner class can extends to different classes.
7. An interface's method can be implemented more than once in different or same ways, using Inner Class.
This pattern is used very often with the builder pattern. It not only makes clear the relation between a class and its builder, but also hides the ugly builder constructor/factory and makes builder more readable. For example in case you need your built object to have optional and not optional properties.
public class AnObject {
public static class AnObjectBuilder {
private AnObject anObject;
private AnObjectBuilder() {
}
private void newAnObjectWithMandatory(String someMandatoryField, ...) {
anObject = new AnObject(someMandatoryField,...)
}
public AnObjectBuilder withSomeOptionalField(String opt) {
...
}
}
public static AnObjectBuilder fooObject() {
return (new AnObjectBuilder()).newAnObjectWithMandatory("foo")
}
public static AnObjectBuilder barObject() {
return (new AnObjectBuilder()).newAnObjectWithMandatory("bar")
}
}
This way the client code have to call first the static method on the AnObjectBuilder class and then to use the optional builder methods:
AnObject.fooObject("foo").withSomeOptionalField("xxx").build(); without creating the builder object.
Pretty readable :)
I was wondering since even the inner class is public why have it as nested and not a separate class?
Have a look at this thread: Why strange naming convention of "AlertDialog.Builder" instead of "AlertDialogBuilder" in Android
Also, can I do this here: new A.B(SomeObject) ?
(Update) No, you can't do this, since B doesn't have a constructor that asks for SomeObject.
I hope this helps.
I was wondering since even the inner class is public why have it as
nested and not a separate class?
The simple reason it is allowed is packaging convenience.
Static nested class in Java, why?
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
yes, you can do new A.B(SomeObject). But you don't have to take my word for it, try it out.
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();
}
}