I am trying to use template design patt开发者_Python百科ern so I use abstract class to define my algorithm like this:
abstract class MyTemplate
{
public void execute()
{
//... do something
doSomething();
}
public abstract void doSomethig();
}
In my code I will create an instanceof MyTemplate everytime like this:
MyTemplate cleanUp = new MyTemplate()
{
public void doSomething()
{
// execute cleanup
}
}
cleanUp.execute();
Is creating a object out of abstract class expensive for JVM?
Thanks,
Sean Nguyen
No, the compiler generates an anonymous inner class at, er, compile time. Instantiating an object of this class is no more expensive than for any other class.
You're not really creating an abstract class instance. You're creating an instance of a concrete class which happens to have no name in your code, created by the Java compiler.
The JVM doesn't really know or care about that - so it's only as expensive as creating an instance of any other class which happens to be a subclass of an abstract class. So don't sweat it :)
Internally, the JVM implements this behavior by having the Java compiler create a new .class file for the anonymous class you created on-the-fly, then instantiating a new object of that type. Consequently, there is a (very small) one-time cost for loading the new class into the JVM, but from that point forward the cost of creating the new object is the same as the cost of creating any other object.
In other words, no, there is not a large inefficiency introduced by this code.
精彩评论