• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

newInstance of abstract class?

 
Ranch Hand
Posts: 44
1
Android Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello, I am looking through a java servlet code.
It is a simple MVC Controller which looks through the init parameters from the web app and instantiate a class.

I don't know how it can work because the class "EventHandlerBase" is an abstract class, yet it is possible to call .newInstance on it?

Here is the code I don't understand:


 
author
Posts: 23949
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Although your code does do a cast to the EventHandlerBase type, it is not clear if it is instantiating the EventHandlerBase class (versus a subclass). Perhaps it would be a good idea to print out the className string, to see exactly what is being instantiated?

Henry
 
Bartender
Posts: 1464
32
Netbeans IDE C++ Java Windows
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Kevin Olome wrote:




I believe Henry has you on the right track to an answer, Kevin. The call to newInstance() can't be creating an instance of EventHandlerBase because, as you have observed, that's an abstract class. But, Class.forName(className).newInstance() will return a reference to an instance of whatever class's name is in the String, className. If that's a subclass of EventHandlerBase, it can be cast to an instance of EventHandlerBase, which is what that line of code does.

So, the short answer to "How is this possible?" is that the line above isn't creating a new instance of an EventHandlerBase object. It's creating an instance of some other class and casting it to an EventHanderBase reference.
 
Stevens Miller
Bartender
Posts: 1464
32
Netbeans IDE C++ Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's a SSCCE that you can run. Maybe it will give you some insight:

reply
    Bookmark Topic Watch Topic
  • New Topic