Reputation: 2814
This works good.
package abstracttest;
public abstract class AbstractClass implements NewInter {
public abstract void doStuff();
public void doStuff2() {
System.out.println("in doStuff2");
}
/*
* public static void main(String a[]) { AbstractClass ab = new
* AbstractClass() {
*
* @Override public void doStuff() { // TODO Auto-generated method stub
* System.out.println(" doStuff "); }
*
* @Override public void doInter() { // TODO Auto-generated method stub
*
* } };
*
* ab.doStuff2(); ab.doStuff();
*
* NewInter ni = new NewInter() {
*
* @Override public void doInter() { // TODO Auto-generated method stub
* System.out.println("do Inter"); }
*
* }; ni.doInter();
*
* AbstractClass ab1 = new AbstractClass(); }
*/
}
interface NewInter {
String con = "Hell";
void doInter();
}
class Impl extends AbstractClass {
@Override
public void doInter() {
// TODO Auto-generated method stub
}
@Override
public void doStuff() {
// TODO Auto-generated method stub
}
public static void main(String[] s) {
AbstractClass ab = new AbstractClass() {
@Override
public void doInter() { // TODO Auto-generated method stub
System.out.println("impl doInter");
}
@Override
public void doStuff() { // TODO Auto-generated method stub
System.out.println("impl doStuff");
}
};
ab.doInter();
ab.doStuff();
NewInter ni1 = new NewInter() {
@Override
public void doInter() {
// TODO Auto-generated method stub
}
};
ni1.doInter();
}
}
I was able to instantiate the abstract class
and interface
both from within the abstract class' main()
and from the class Impl
.
How is this possible?
I was expecting an exception but the invocation worked correctly.
Can someone please explain the phenomena? I am confused.
A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
I read this in a blog. What does it mean?
And is there any other way of invoking the constructor of an abstract class? Please let me know if there is.
Upvotes: 2
Views: 2331
Reputation: 272247
If I do this:
new AbstractClass() {
public void methodToImplement() {
}
}
it's creating an anonymous class derived from the abstract class. It's so called (anonymous) since the class definition doesn't have it's own accessible name and you can't access the definition again. The definition/instantiation occur together e.g.
AbstractClass ac = new AbstractClass() {
...
}
(it's a subclass of AbstractClass
)
Note that you can do this for both interfaces and abstract classes, but you'll have to implement the required methods appropriately.
The above is often used to implement simple interfaces/abstract classes in a concise form, often as inner classes within callbacks. See this SO question for more info, and the Nested Class tutorial for more discussion.
Upvotes: 8
Reputation: 32391
No, you didn't instantiate them. You have only created anonymous classes that implement the interface or extend the abstract class. Objects of these anonymous classes types are actually instantiated.
Upvotes: 14