Creating the instance of abstract class or anonymous class
Solution 1:
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;
}
};
Solution 2:
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;
}
};
- New class was defined (without a name, so called anonymous class)
- This new class extends
AbstractDemo
class - Abstract methods of
AbstractDemo
were overriden in this new class - New instance of this new class was created and assigned to
ad
variable
Read more about anonymous classes
in Java here.
Solution 3:
You can not create an instance of an abstract class.
You can create an instance of a class that extents your abstract class.
The whole point of an abstract class is that it's abstract -- you've defined an interface but not an implementation. Without an implementation, instantiating the class wouldn't produce a meaningful or useful result. If it does/would make sense to instantiate objects of that class, then you simply don't want to use an abstract class in the first place.
You can use anonymous class concept for an instance like the below:
AbstractDemo abstractDemo = new AbstractDemo() {
@Override
void showMessage() {
// TODO Auto-generated method stub
}
@Override
int add(int x, int y) {
// TODO Auto-generated method stub
return 0;
}
};
Solution 4:
@Override // Here
void showMessage() {
// TODO Auto-generated method stub
}
@Override // here
int add(int x, int y) {
// TODO Auto-generated method stub
return 0;
}
first of all you have to know that you can't create an instance
for abstract class
, here you are just creating a anonymous class
which is act like a inner class
that extends the abstract class
so its belongs to your anonymous class
.