In this code here is it creating the object of abstract class or anonymous class? Please tell me. I am little bit confused here.
public abstract class AbstractDemo {
abstract void showMessage();
abstract int add(int x,int y);
public int mul(int x,int y){
return x+y;
}
public static void main(String[] args) {
AbstractDemo ad = new AbstractDemo() {
@Override
void showMessage() {
// TODO Auto-generated method stub
}
@Override
int add(int x, int y) {
// TODO Auto-generated method stub
return 0;
}
};
System.out.println(ad.mul(10, 12));
System.out.println(ad.getClass());
}
}
Anonymous classes are inner classes with no name. Since they have no name, we can't use them in order to create instances of anonymous classes. As a result, we have to declare and instantiate anonymous classes in a single expression at the point of use. We may either extend an existing class or implement an interface.
Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .
In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways: Class (may be abstract or concrete).
You cannot create an instance of an interface or an abstract class in Java. But you can create anonymous classes that implement an interface or an abstract class.
You create an anonymous class that extends your abstract class.
In the snipped below, you are extending AbstractDemo
and provide implementations for its abstract methods.
new AbstractDemo() {
@Override
void showMessage() {
// TODO Auto-generated method stub
}
@Override
int add(int x, int y) {
// TODO Auto-generated method stub
return 0;
}
};
Here's what happened in this short and innocent piece of code:
AbstractDemo ad = new AbstractDemo() {
@Override
void showMessage() {
// TODO Auto-generated method stub
}
@Override
int add(int x, int y) {
// TODO Auto-generated method stub
return 0;
}
};
AbstractDemo
classAbstractDemo
were overriden in this new classad
variableRead more about anonymous classes
in Java here.
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