What is the use of anonymous inner classes ?

Answer Posted / ram

You need object of class 'X', but you want some custom
behavior for the object, not following the behavior defined
by the class 'X'.
Solution 1: create subclass 'Y' extending 'X'. Override
required methods(for custom behavior). create instance of Y
in your code and use it.
Solution 2: But you can achieve the above thing (need a
instance with different behavior) using anonymous inner
classes. The advantage here is, you don't even need to
create a subclass. Create an Anonymous inner class on the
fly, Just override the required behavior, and create an
instance and use it. Here is an example :

I have a class 'A'. By default, its getValue() method
returns whatever the value x holds. But i want to override
this behavior, it should return x+15.

public class AnonymousInnerClass {

public static void main(String[] args) {
A a = new A(10) {
@Override
public int getValue() {
return x + 15;
}
};
System.out.println(a.getValue());// 25 and not 10
}

}

class A {
int x;

public int getValue() {
return x;
}

A(int x) {
this.x = x;
}
}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How do you check if an arraylist is not empty?

571


How do you generate random numbers in java?

508


If goto and const is reserve words than why it is not work in java?

1502


Can a class be private or protected in java?

547


Discuss about garbage collector in Java.

640






What are the library functions in java?

542


What are encapsulation, inheritance and polymorphism?

523


What is passing value java?

506


Which is easier .net or java?

641


When do we need to use internal iteration? When do we need to use external iteration?

603


How can we create an immutable class in java?

579


What is main in java?

504


What are parsers? Dom vs sax parser.

555


What is meant by distributed application? Why are we using that in our application?

543


What is thread safe singleton?

511