Say I'm using a Runnable interface,
Runnable runnable = new Runnable() {
#Override
public void run() {
// some code
}
};
If the run () method in Runnable interface is empty , why should we use #Override and same name for the method in our code instead of just using a random name for our implementation like ,
Runnable runnable = new Runnable() {
public void myRun() {
// some code
}
};
The question might seem dumb but I'm a newbie to programming!
Runnable has only one method, thus, you may be tempted to think the method name is irrelevant. But most interfaces have more than one method. For example, java.util.Iterator which has 2 (well, 4, but 2 of those have default impls so you don't need to implement those. Point is, 2 that you must implement).
So, let's say that instead of naming your two methods next and hasNext, you name them jill and jane instead.
How is the compiler or any caller supposed to figure out which one performs the hasNext job and which one performs the next job? Look at the signatures? What if your interface has 2 different methods with the exact same signature?
Not possible. That's why the names need to match: They are used to look this up.
Yes, if the interface has just the one name you'd think the compiler/caller can just go: Yeah, well, the one and only method it has, that's the one. But that's not how it works - language design is simpler if you avoid making exceptions just for simplified cases.
Note that java has lambda syntax, which only works when an interface has one method, and which omit the method name entirely, as well as the argument types. Instead of your myRun method you could write this too:
Runnable r = () -> /* some code */;
No new Runnable() { public void myRun, and no }} required. If myRun had arguments, you don't even need to add their types, just their names. For example, Comparator, which has arguments:
long form:
Comparator<String> lengthComparator = new Comparator<String>() {
#Override public int compare(String a, String b) {
return a.length() - b.length();
}
};
can be written much shorter:
Comparator<String> lengthComparator = (a, b) -> a.length() - b.length();
Think about what it means to "implement an interface". If I have a variable of an interface type, I can call any method defined in the interface on that variable. For example, for the Runnable interface:
interface Runnable {
void run();
}
If I have a variable of type Runnable, I know I can call run on it:
Runnable r = ...;
r.run(); // I can guarantee this will work, because whatever "..." evaluates to, implements Runnable
So when you implement Runnable, you are really just saying that "this class has a run method". The Java compiler also checks that what you are saying is true, that the class actually has a run method. Saying false things about your class, intuitively, should not be allowed, right?
We can also think about what would happen if you were allowed to implement Runnable, but not provide a run method, then you would not be 100% sure that any variable of type Runnable has a run method.
class TrueRunnable implements Runnable {
#Override public void run() {}
}
class FakeRunnable implements Runnable { // suppose this is allowed
public void myRun() {}
}
...
Runnable r;
if (new Random().nextBoolean()) {
r = new TrueRunnable()
} else {
r = new FakeRunnable();
}
// does r have a run method? Maybe.
Then interfaces would not be very useful, because you are not 100% sure whether any Object has any method anyway.
Object r;
if (new Random().nextBoolean()) {
r = new TrueRunnable()
} else {
r = new FakeRunnable();
}
// does r have a run method? Maybe.
So in that case we would lose the whole point of using interfaces.
As to why an interface implementation method has to have the same name as the declaration method name in the interface , i think it boils down to allowing Java compiler to understand which method actually implements the interface. Otherwise its impossible for the Java compiler to know.
Another solution could have been to use a qualifier name in an annotation to signal which is the implementation method something like this.
public interface MyInterface {
void sayHello();
}
and
public class Hello implements MyInterface {
#Implements("MyInterface.sayHello")
public void someOtherName() {
print("Hello World);
}
}
This approach is not valid , but could have been an alternative if Java creators wanted to allow users to declare different names for interface implementation methods. I think this approach is uglier and prone to errors though.
Also this problem does not exist when using lambda expressions where the compiler can understand whats happening without the code writer having to specify the name of the interface method. Note that this only applies to functional interfaces.
I am little bit confused with the different behavior of an anonymous class and a lambda expression.
When I'm using a lambda expression:
//Test.java
Runnable r1 = () -> System.out.println(this);
Runnable r2 = () -> System.out.println(toString());
#Override
public String toString() {
return "Hello World!";
}
// in main method
new Test().r1.run();
new Test().r2.run();
Output : Hello World!
Hello World!
When using an anonymous class:
Runnable r1 = new Runnable() {
#Override
public void run() {
System.out.println(this);
}
};
Runnable r2 = new Runnable() {
#Override
public void run() {
System.out.println(toString());
}
};
#Override
public String toString() {
return "Hello World!";
}
// in main method
new Test().r1.run();
new Test().r2.run();
Output : Package_Name.Test$1#1db9742
Package_Name.Test$2#106d69c
Can someone please explain the different behavior?
In a lambda expression, this is lexically bound to the surrounding class, while in the anonymous class this is lexically bound to the anonymous class.
The Java Language Specification describes this behavior at 15.27.2:
Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).
The transparency of this (both explicit and implicit) in the body of a lambda expression - that is, treating it the same as in the surrounding context - allows more flexibility for implementations, and prevents the meaning of unqualified names in the body from being dependent on overload resolution.
Practically speaking, it is unusual for a lambda expression to need to talk about itself (either to call itself recursively or to invoke its other methods), while it is more common to want to use names to refer to things in the enclosing class that would otherwise be shadowed (this, toString()). If it is necessary for a lambda expression to refer to itself (as if via this), a method reference or an anonymous inner class should be used instead.
In order to reference this of the surrounding class from inside an anonymous class, you will have to use a qualified this.
Runnable r1 = new Runnable() {
#Override
public void run() {
System.out.println(Test.this); // or Test.this.toString()
}
};
What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.
I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
public interface F<A, B> {
B f(A a);
}
You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:
public static int larger(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n > i)
return n;
return i;
}
And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:
public static int smaller(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n < i)
return n;
return i;
}
These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:
public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
for (T t : ts)
if (f.f(t))
return t;
return z;
}
You can use an anonymous class to use the firstMatch method:
F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
Boolean f(final Integer n) {
return n > 10;
}
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);
This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.
A nice library for programming Java in this style: Functional Java.
Anonymous inner class is used in following scenario:
1.) For Overriding(subclassing), when class definition is not usable except current case:
class A{
public void methodA() {
System.out.println("methodA");
}
}
class B{
A a = new A() {
public void methodA() {
System.out.println("anonymous methodA");
}
};
}
2.) For implementing an interface, when implementation of interface is required only for current case:
interface InterfaceA{
public void methodA();
}
class B{
InterfaceA a = new InterfaceA() {
public void methodA() {
System.out.println("anonymous methodA implementer");
}
};
}
3.) Argument Defined Anonymous inner class:
interface Foo {
void methodFoo();
}
class B{
void do(Foo f) { }
}
class A{
void methodA() {
B b = new B();
b.do(new Foo() {
public void methodFoo() {
System.out.println("methodFoo");
}
});
}
}
I use them sometimes as a syntax hack for Map instantiation:
Map map = new HashMap() {{
put("key", "value");
}};
vs
Map map = new HashMap();
map.put("key", "value");
It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.
They're commonly used as a verbose form of callback.
I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)
Here's a swing example
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// do stuff here...
}
});
Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)
You use it in situations where you need to create a class for a specific purpose inside another function, e.g., as a listener, as a runnable (to spawn a thread), etc.
The idea is that you call them from inside the code of a function so you never refer to them elsewhere, so you don't need to name them. The compiler just enumerates them.
They are essentially syntactic sugar, and should generally be moved elsewhere as they grow bigger.
I'm not sure if it is one of the advantages of Java, though if you do use them (and we all frequently use them, unfortunately), then you could argue that they are one.
GuideLines for Anonymous Class.
Anonymous class is declared and initialized simultaneously.
Anonymous class must extend or implement to one and only one class or interface resp.
As anonymouse class has no name, it can be used only once.
eg:
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
Yes, anonymous inner classes is definitely one of the advantages of Java.
With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.
But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).
new Thread() {
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println("Exception message: " + e.getMessage());
System.out.println("Exception cause: " + e.getCause());
}
}
}.start();
This is also one of the example for anonymous inner type using thread
An inner class is associated with an instance of the outer class and there are two special kinds: Local class and Anonymous class. An anonymous class enables us to declare and instantiate a class at same time, hence makes the code concise. We use them when we need a local class only once as they don't have a name.
Consider the example from doc where we have a Person class:
public class Person {
public enum Sex {
MALE, FEMALE
}
String name;
LocalDate birthday;
Sex gender;
String emailAddress;
public int getAge() {
// ...
}
public void printPerson() {
// ...
}
}
and we have a method to print members that match search criteria as:
public static void printPersons(
List<Person> roster, CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}
where CheckPerson is an interface like:
interface CheckPerson {
boolean test(Person p);
}
Now we can make use of anonymous class which implements this interface to specify search criteria as:
printPersons(
roster,
new CheckPerson() {
public boolean test(Person p) {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
}
);
Here the interface is very simple and the syntax of anonymous class seems unwieldy and unclear.
Java 8 has introduced a term Functional Interface which is an interface with only one abstract method, hence we can say CheckPerson is a functional interface. We can make use of Lambda Expression which allows us to pass the function as method argument as:
printPersons(
roster,
(Person p) -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);
We can use a standard functional interface Predicate in place of the interface CheckPerson, which will further reduce the amount of code required.
i use anonymous objects for calling new Threads..
new Thread(new Runnable() {
public void run() {
// you code
}
}).start();
Anonymous inner class can be beneficial while giving different implementations for different objects. But should be used very sparingly as it creates problem for program readability.
One of the major usage of anonymous classes in class-finalization which called finalizer guardian. In Java world using the finalize methods should be avoided until you really need them. You have to remember, when you override the finalize method for sub-classes, you should always invoke super.finalize() as well, because the finalize method of super class won't invoke automatically and you can have trouble with memory leaks.
so considering the fact mentioned above, you can just use the anonymous classes like:
public class HeavyClass{
private final Object finalizerGuardian = new Object() {
#Override
protected void finalize() throws Throwable{
//Finalize outer HeavyClass object
}
};
}
Using this technique you relieved yourself and your other developers to call super.finalize() on each sub-class of the HeavyClass which needs finalize method.
You can use anonymous class this way
TreeSet treeSetObj = new TreeSet(new Comparator()
{
public int compare(String i1,String i2)
{
return i2.compareTo(i1);
}
});
Seems nobody mentioned here but you can also use anonymous class to hold generic type argument (which normally lost due to type erasure):
public abstract class TypeHolder<T> {
private final Type type;
public TypeReference() {
// you may do do additional sanity checks here
final Type superClass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
public final Type getType() {
return this.type;
}
}
If you'll instantiate this class in anonymous way
TypeHolder<List<String>, Map<Ineger, Long>> holder =
new TypeHolder<List<String>, Map<Ineger, Long>>() {};
then such holder instance will contain non-erasured definition of passed type.
Usage
This is very handy for building validators/deserializators. Also you can instantiate generic type with reflection (so if you ever wanted to do new T() in parametrized type - you are welcome!).
Drawbacks/Limitations
You should pass generic parameter explicitly. Failing to do so will lead to type parameter loss
Each instantiation will cost you additional class to be generated by compiler which leads to classpath pollution/jar bloating
An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement.
This is used where you would normally use an object's variable. You replace the variable with the new keyword, a call to a constructor and the class definition inside { and }.
When writing a Threaded Program in Java, it would usually look like this
ThreadClass task = new ThreadClass();
Thread runner = new Thread(task);
runner.start();
The ThreadClass used here would be user defined. This class will implement the Runnable interface which is required for creating threads. In the ThreadClass the run() method (only method in Runnable) needs to be implemented as well.
It is clear that getting rid of ThreadClass would be more efficient and that's exactly why Anonymous Inner Classes exist.
Look at the following code
Thread runner = new Thread(new Runnable() {
public void run() {
//Thread does it's work here
}
});
runner.start();
This code replaces the reference made to task in the top most example. Rather than having a separate class, the Anonymous Inner Class inside the Thread() constructor returns an unnamed object that implements the Runnable interface and overrides the run() method. The method run() would include statements inside that do the work required by the thread.
Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.
References: Sams Teach Yourself Java in 21 Days Seventh Edition
The best way to optimize code. also, We can use for an overriding method of a class or interface.
import java.util.Scanner;
abstract class AnonymousInner {
abstract void sum();
}
class AnonymousInnerMain {
public static void main(String []k){
Scanner sn = new Scanner(System.in);
System.out.println("Enter two vlaues");
int a= Integer.parseInt(sn.nextLine());
int b= Integer.parseInt(sn.nextLine());
AnonymousInner ac = new AnonymousInner(){
void sum(){
int c= a+b;
System.out.println("Sum of two number is: "+c);
}
};
ac.sum();
}
}
One more advantage:
As you know that Java doesn't support multiple inheritance, so if you use "Thread" kinda class as anonymous class then the class still has one space left for any other class to extend.
Can you build nested functions in Processing (Java?)
This code doesn't work. The compiler reads: unexpected token: void.
void keyPressed() {
if(click1 = true) {
graph();
}
if(click2= true) {
points();
}
void graph() {
....
....
}
}
You can't have nested functions. You can have anonymous classes, for example in a new thread:
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// This is all in an anonymous Runnable class.
}
});
Like others have said: no, you can't have "local functions" like that.
You also aren't doing your boolean comparison correctly, as a single = is assignment, not comparison. It should be either:
if(click1 == true) {
Or since you're already working with booleans, you can refer to it directly:
if(click1) {
Anyway, back to your question: you can't do what you're talking about, but you can get around it by using an anonymous class. To use an anonymous class, you need to have an existing class that you want to extend by overriding one or more of its functions, which you can do inside a method.
For example, we have the Runnable interface that we can implement by defining an anonymous class that defines the run() method, and then call that anonymous class directly. It looks like this:
void keyPressed() {
if(click1) {
new Runnable(){
public void run(){
//do graph stuff here
}
}.run();
}
if(click2) {
new Runnable(){
public void run(){
//do points stuff here
}
}.run();
}
}
More info on anonymous inner classes here: http://staticvoidgames.com/tutorials/objects/advancedInheritance
However, all of this has a pretty bad code smell, and isn't the way any sane person would do this. Why do you think you need a local method? Chances are you should either use separate classes, or a regular old top-level method.
I'm currently taking a course in Java and I've run into some confusing code.
Example:
Runnable runnable = new Runnable()
{
public void run()
{
//doStuff
}
};
I don't really get what this code is doing.
How can the run method be associated with an instance of a class?
I googled "Runnable" and found out that it is an interface. Am I implementing the interface by declaring the run method between curly brackets ? Can this be done for any interface in java ?
I could use some links/explanations. Thank you!
It's an anonymous inner class that's implementing the interface Runnable. Yes, you can implement any interface this way, although there are reasons why you would or wouldn't in any given case (lack of reusability being a big one in the "wouldn't" column). More about anonymous classes here, but it's basically a convenient form of this:
// Define it
class Foo implements Runnable
{
public void run()
{
// Do stuff
}
}
// And then use it
Runnable runnable = new Foo();
...provided Foo is an inner (or "nested") class. More about nested classes here.
yes, you are implementing the interface by declaring the run. Yes it can be done for any interface.
This is typically done when you pass an implementation to a method that expects an argument of an Interface type, and you don't have a declared class that is appropriate. You can just implement the interface on the spot, and that code runs. Pretty neat.
I googled "Runnable" and found out
that it is an interface. Am I
implementing the interface by
declaring the run method between curly
brackets ? Can this be done for any
interface in java ?
Yes!
This code is instantiating an object which implements Runnable. Because we can't actually construct an interface, any code which attempts to do so must provide implementations for the interface's methods in curly brackets. We don't really get to see what class Java is creating to implement Runnable (these are abstract terms).
If you were to do the following:
Runnable runnable = new Runnable()
{
public void run()
{
System.out.println("I'm running");
}
};
runnable.run();
you would see "I'm running" as your output.
In some situation , this sample code will be useful .... test runna = new test()
class test implements Runnable{
test(){
Thread t = new Thread(this);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("asd");
}
}
}