| Author |
Extending a singleton class
|
Ankur Sharma
Ranch Hand
Joined: Dec 27, 2005
Posts: 1234
|
|
Hi, I have a class(e.g. SuperClass), which is singleton. Now I want to create a sub singleton class(e.g. SubClass) from SuperClass with some specific new methods, which may use some SuperClass.methods() too. I am giving below details about my class, and what I have done so far. but it's not working(I mean it's giving compilation error) SUPER_CLASS Here is SUB_CLASS, I am trying to create SUB_CLASS But this code is not compiling properly, as it's giving following compilation error @ AnaylsisTestDAO getInstance() method
The return type is incompatible with UnrecognizedDataDAO.getInstance()
I hope, I illustrated my problem very well, but still if anything disturbs you, just let me know. I will try again to voice my concern. Thanks
|
The Best way to predict your future is to create it
Ankur Sharma
|
 |
Alex Wong
Greenhorn
Joined: Jul 27, 2007
Posts: 4
|
|
|
The return type for getInstance() within AnalysisTestDAO should be UnrecognizedDataDAO, not AnalysisTestDAO. Otherwise, you're trying to have a method with the same name and parameters but with different return types (since there is a already a getInstance method in the superclass). The rest of your code should be okay as-is, since AnalysisTestDAO is a UnrecognizedDataDAO; just remember to cast the returned object to an AnalysisTestDAO when you call AnalysisTestDAO.getInstance().
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32644
|
|
Extend a Singleton? Surely that is a contradiction in terms. Your Singleton is supposed to have one instance and one only; an instance of a subclass would represent a second instance of the original Singleton too. And wouldn't a Singleton have a private constructor? In which case you cant extend it. I also think this isn't a real beginner's topic, so I shall move it.
|
 |
Bill Shirley
Ranch Hand
Joined: Nov 08, 2007
Posts: 457
|
|
Some languages don't inherit static methods, they are basically just scoped. They would allow what you want. But Java DOES inherit static methods (you can call SubClass.staticMethodFromParentClass() � ) and changing the return type of an overriden method is a no-can-do. If what you're saying is really what you want to do, then you likely want to rename the static methods to getFooInstance() and getBarInstance(). But as mentioned, your Singleton implementation is a bit fragile. Google around for some examples.
|
Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
|
 |
 |
|
|
subject: Extending a singleton class
|
|
|