Why not singleton instance provided out of box in java? [closed] - java

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
You can make class singleton by implementing Singleton pattern. Nowadays singleton class is basic requirement.
Why don't JVM handles Singleton object creation by itself at runtime?
By having marker interface like "Singleton" and creating object instance once by JVM at runtime. Anyways Java compiler adds "extends Object" if Class is not extending any other class. Similar approach can be applied in Singleton case.
This will save lot of time and development effort and discussions around various implementations of Singleton pattern.
1) Synchronized getInstance()
2) Synchronized block inside getInstance() instead of making whole method synchronized
3) Option 2 with singleInstance as volatile member
This will also save lot of time and duplicate efforts if you need to implement singleton pattern in multiple classes(not considering SingletonPatternFactory class which will return singleton instance of any class which is been passed)

Let's take a look at all of the steps needed to create a singleton:
private constructor
a static final field
(optional) if you want the class to be serializable, trivial implementations of readResolve and writeObject
Most singletons that I've come across don't care about serialization, so that third step isn't needed. This leaves you two really, really easy steps.
public class Whatever extends WhateverElse {
public static final Whatever INSTANCE = new Whatever();
private Whatever() {}
}
It's even lazy-loaded, since the constructor won't be run until you access the class, which would only be to get the singleton instance of it. I don't know what your definition of "a lot" is as far as time and development effort, but I don't consider this to be onerous.

Implementing basic design patterns is not the responsibility of the core language, unless there is a compelling reason it should be. Design patterns come and go -- for example, the singleton pattern is widely regarded as an extremely bad pattern that should never be used. Even if you decide to use it anyway, do you want an eager singleton? Lazy singleton? What should happen if instantiation fails for some reason? There's a whole lot of seemingly minor issues to cover, but adding this feature to the language is not a trivial change.
By implementing it yourself you get exactly the features and behavior you want.

You can use an enum instead of a singleton pattern - this is not very complex:
public enum Singleton {
INSTANCE;
}

There are two basic categories of Singletons, those with lazy initialization and those with eager initialization.
Aside from the whole argument on flavors of Singletons, many Java developers consider Singletons to be bad or an anti-pattern. This is probably an area of disagreement among those currently maintaining the Java spec.
Lastly, the same could be said true of most any pattern. There is not a huge need for a language to adopt or endorse any specific set of patterns, IMHO.

You would not want a Singleton interface, since the interface has no behavior of its own. You would want an abstract class... kind of. In reality you would want something a lot more powerful than just an abstract parent. You need to have a private constructor (or a private instantiation method that calls a private constructor and returns the single instance) that has to be called in the getInstance() method defined in the parent (violation of scoping).
What you are suggesting is something that will work outside of the traditional class system. Perhaps it can be done as a new object type (similar to how an enum is not a class), but definitely not as a standard interface or class.

Related

Java Interface Naming Conventions [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I work on a Java web-app that uses Spring for dependency injection and JMock for mocking out these dependencies in our unit tests.
Currently our team is at a point were we have a few different opinions in terms of how to name certain interfaces that we use. We have no issue with naming the interfaces in our domain that have multiple implementations, that is simple. However, when it comes to interfaces for which we only have one implementation and intend on only having one implementation in the future, we have hit a snag.
The reason that we have such interfaces is purely for mocking, for example, we have services and repositories that we mock out in our unit tests and these services will be named "DocumentMappingService" or for repositories "EmployeeRepository". At the moment some of the guys just prefix the associated interface name with an "I", i.e. "IDocumentMappingService" and "IEmployeeRepository". Others name the interface as I have above and then append an "Impl" after the interface name for the implementing class.
The third "faction" feels that both of these options are poor. Looking at literature such as the well-known "Growing object-oriented software, guided by tests" would lead one to believe that both of the before-mentioned options are poor and that the interface name should clearly define the contract and the implementing classes name should clearly specify how that contract has been implemented. We have found this quite difficult to do in the case I have mentioned above though.
I was hoping that someone out there has had a similar issue before and has some suggestions ito which option is the best and why. Also, if you think that the "I" and "Impl" options are both poor, then please suggest a specific alternative convention.
There's no "one" correct answer here. Naming is quite subjective but what matters the most is that it should be consistent throughout the code base. I would just like to add (to #fge's answer) some more options for you:
Making the Interfaces more generic.
EmployeeRepository implements Repository
DocumentMappingService implements MappingService
Calling your single implementations "defaults".
DefaultEmployeeRepository implements EmployeeRepository
DefaultDocumentMappingService implements DocumentMappingService
Calling your base implementations (if, sometimes extended) as "support".
EmployeeRepositorySupport implements EmployeeRepository
DocumentMappingServiceSupport implements DocumentMappingService
I come across these naming conventions a lot when using the Spring Framework.
Edit : In response to user nyxz's comment about the -Base or Base- convention.
Like I said before, naming is subjective and there's nothing wrong with using the Base nomenclature as such. But, personally, I don't prefer using it. Here's why:
If your implementations would mostly be used directly, then the code instantiating the classes leaves an impression of breaking the OOP hierarchy. That perhaps a specific derived class should have been instantiated.
If your implementations would mostly be extended from, then the word Base becomes redundant in a way. You're extending from it so, of course, it's a base class. Duh!
The 2nd point mostly applies to peripheral classes in your project. Extension points that you provide when you're publishing a framework or library to be used and extended in other projects.
On the other hand, a good use case for using the Base terminology would be for classes internal to your framework that factor common functionality out of other peripheral classes. Since, these classes aren't supposed to be instantiated directly, they are marked abstract, which is in line with the 1st point.
Here's the Adapter hierarchy from the Android framework as an example:
Interface hierarchy.
public interface Adapter
public interface ListAdapter extends Adapter
public interface SpinnerAdapter extends Adapter
The abstract Base class that factors out the common behaviour and interface implementations.
public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter
Peripheral classes that are mostly instantiated but sometimes extended by an Android application.
public class SimpleAdapter extends BaseAdapter implements Filterable
public class ArrayAdapter<T> extends BaseAdapter implements Filterable
An answer to such a question can only reflect the tastes of the person who answers... So these are my tastes:
I hate the initial I. It brings nothing of value to the picture. It reminds me of the Hungarian notation where float variables were to be suffixed with _f or the like. No.
The Impl suffix is good enough. But on the other hand, it sounds weird.
I'd suggest two alternate proposals for a given interface Foo:
create a single implementation but not with the Impl suffix; find a more "appealing" name. For instance, TheOnlyOneFoo;
create a factory with an appended s: Foos. Then, a Foo instance would be a Foos.newInstance(whatever, args).
I prefer the second solution, for two reasons:
it can hide the fact that the real implementation has an ugly name;
it can be extended easily when you realize one day that "no, after all, there is more than one implementation for that": just add another static factory method; and if the only existing method in existence sounds too generic, you can just mark it as #Deprecated.
It could even be used in a manner so that all Foo implementations are package local, or even private to the factory. But stack traces would look worse...
No real solution there ;)
edit: as for mocking:
I'd recommend mockito. Really. It is very easy to use, and very powerful.
If those are "one-implementation classes" you are dealing with, maybe there is a better alternative in the JDK itself? What is it that you want to do exactly? The JDK has hidden treasures...
And as a final note... Have you considered the builder pattern?

in which scenario abstract class and interface should not be used? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have been asked in interview in which scenario abstract class and interface both should not be used ?
I wasn’t able to clearly answer his question with specific examples of when you would not want to do this, at the time. I have search lot for specific answer with example but unable to find.
I know when to use which one. Also I understand that
abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time.
So can I answer that when I don't found any relation then i should not use it.
Can you genious guys spend a minute and answer me to increase my knowledge?
Thanks in advance.
One anti-pattern that comes to mind is where constants (as public static final variables) are put on either an abstract class and an interface, and then the users of these constants implement the interface or extend the abstract class. The so-called advantage of this was that the constants did not need to be qualified every time they were used. e.g. MyConstants.MY_VALUE vs MY_VALUE
With Java 1.5 and later, static imports can now be used to avoid having to qualify the constant with a class name. Though personally I don't really mind qualifying constants with a class name especially if the constants' class names have a meaningful 'grouping' name.
Perhaps when you explicitly want just one implementation, so that you don't maintain two versions of the same thing. One might also make the class final in this situation.
I have one idea. Probably if your class contains a set of static utilities. For example StringUtils. But anyway I think that the question as you wrote it does not have too much sense.
2 cases I think
1 : if you have to instantiate objects of your class (eg: MyClass object=new MyClass())
2 : in case of inheritance of the same implementation as the parent class eg:
class Parent {
int x;
public void setX(int x) {
this.x = 2 * x;
}
}
class Child extends Parent {
int y = 1;
public void setX_AND_Y(int x, int y) {
setX(x); // same implmentaion
this.y = y;
}
}
I had some issues with spring bean that had to implement interface and extend some base class in the past.
This was rather an advanced problem related to AOP and Spring, so I cannot be 100% sure that this is what your interviewer asked, but it is totally something you can stumble upon in the wild, and not limited only to Spring.
Often you want to add AOP to your Spring application (for example to use #Transactional annotations). The problem is that there are couple of ways how AOP can be implemented, from patching bytecode at compile time or loadtime, to generation something similar to wrappers at runtime.
The latter approach is the most cheap, build-structure-wise, and used more commonly than others but it has it's disadvantages.
One of them is that there are plenty of ways to do this and approach differ from what exact bean (class instance) you want to weave (wrap). Thing like "whether class implements interface", "whether class extends class" and combinations matter here.
I won't delve deep into details here, simply because I struggled with this pretty while ago, but you can get a grasp of what you'll have to deal with from spring docs briefly discussing this matter.
I will say though that in my project things went wrong when I decided to add class that extended another class and implement some interface. It was quite a challenge to make things work, because you have to have really decent understanding of how Spring itself and AOP weaving techniques work and how to configure all these things so they work as expected.
UPDATE: Answering your question in one sentence: You probably do not want to extend abstract class and implement interface at the same time in the code that deals with dynamic class proxying/AOP/code generation.

Singleton v/s class with static members & methods in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between static class and singleton pattern?
Why would one ever require one and only one instance? Same purpose can be achieved using classes with static member variables and static methods.
As far as I can find out, there might be two possible answers to it -
When your class needs to have state and you want only one object of it. From the design point of view, class with static methods & variables are considered to be the Utility classes and shouldn't be keeping any state.
If your class needs to take part in polymorphism and you want only one object of the class(es) which are in the inheritance tree.
It would be really helpful if someone can provide an example from real life scenario or from any Java API where Singleton objects need to participate in Polymorphism / Inheritance?
Collections.emptySet() is a typical example of a singleton that can't be implemented as a static class since, obviously, its goal is to be an instance of the java.util.Set interface. It's not costly to create, but it would be stupid to create a new instance each time an empty set is needed, since the unique instance can be reused.
Classes that perform logging or common access to data bases frequently follow the Singleton pattern. Basically anything that should have instance methods and that is costly to construct.
Scope and behavior are different concerns and should NOT be mixed. You may want your object to be available per use, per thread, per web request, per session or global (Singleton). The reasons for making these adjustments are likely due to resource management and ultimately performance. The behavior inside your class shouldn't have to change if you change its scope.
Singleton is pattern for taking a regular object and controlling its scope with just a little bit of bolt-on code. Ideally though, you really shouldn't really deal with scope at all inside your object and delegate that to a factory or container.
My answer is quite short but it's enough to use exactly common singleton instead of it's static implementation. The answer is:
Popular paradigm (yes it is!)
Threads (synchronization etc.)
Interface implementation (your static class has some restrictions)

Singleton and Static Utility classes [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
What factors influence the appropriate design pattern to use?
Clarification:
The reason I ask this question is because I'm designing an application that requires multiple static factory classes and singleton manager classes. At times, I become confused as to which design I should employ and I thought asking this community why and when may help clarify things for me a bit.
Singleton is used when a single object needs to be instantiated and all requested object access goes through this particular instance. This object can maintain state if desired.
Static Utility is used when you have a class that is just stateless utility functions.. it does not maintain state. An instance of the object is never instantiated.
I use static utility classes for shared functions that will be called from many different contexts - e.g. maths functions similar to those in java.util.Math. This is an appropriate pattern assuming that these are "pure" functions (i.e. don't manipulate any state or access any data other than than the parameters they are given).
I very rarely use singletons, and in particular try to avoid global singletons. They suffer from all the usual problems associated with global variables. They make testing difficult, and unless your singleton is also immutable they introduce problems of global state. The main place I have found them useful is in performance hacks that depend on object identity - for example:
public static final END_OF_SEQUENCE_MARKER=new EndMarker();
Then when traversing a sequence you can just test if (object==END_OF_SEQUENCE_MARKER). Because it's a static final reference, the JIT will turn this into an extremely fast test....
EDIT
Having just seen your clarification, some quick extra comments:
Static factory classes don't usually make sense. The whole point of a factory class is that you can instantiate it (or a subclass!), make some configuration changes on the factory object, then use it to generate object instances according to the configuration that you need. If you're going to make it static, you might as well just create a static MyObject.create(..) method rather than having a whole static MyObjectFactory class....
Likewise, why have a separate singleton manager class? Usually the best class to manage the singleton is the singleton class itself, since you will typically need it to access a private constructor, assuming you want to guarantee that only one instance will ever be created. Just having a simple static MySingleton.getInstance() method will usually do everything that you need.
IMO static utility classes chalk down a concrete contract between the caller and the class. This is different than singletons wherein you can change the implementation behind the scenes to make your so called 'singleton' provider hand out a new instance each time a call to getInstance is made.
So yes, basically use static utility methods when you are damn sure (e.g. Math) you'd never need an instance and use singletons when you think that a single instance is good enough for the time being but might change in the future (e.g. connection providers).
I'm not sure what the question is here.
Singleton patterns are used where the instance has state that may be preserved or altered across a number of calls - this might be a connection pool or some other shared object that the class provides access to.
Static utility classes are used where each individual method is stateless, and has no bearing on the other methods that the class provides.

Why java.lang.Object is not abstract? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: Rationale of the Object class not being declared abstract
Why is the Object class, which is base class of 'em all in Java, not abstract?
I've had this question for a really really long time and it is asked here purely out of curiosity, that's all. Nothing in my code or anybody's code is breaking because it is not abstract, but I was wondering why they made it concrete?
Why would anyone want an "instance" (and not its presence a.k.a. Reference) of this Object class? One case is a poor synchronization code which uses the instance of an Object for locking (at least I used it this way once.. my bad).
Is there any practical use of an "instance" of an Object class? And how does its instantiation fit in OOP? What would have happened if they had marked it abstract (of course after providing implementations to its methods)?
Without the designers of java.lang.Object telling us, we have to base our answers on opinion. There's a few questions which can be asked which may help clear it up.
Would any of the methods of Object benefit from being abstract?
It could be argued that some of the methods would benefit from this. Take hashCode() and equals() for instance, there would probably have been a lot less frustration around the complexities of these two if they had both been made abstract. This would require developers to figure out how they should be implementing them, making it more obvious that they should be consistent (see Effective Java). However, I'm more of the opinion that hashCode(), equals() and clone() belong on separate, opt-in abstractions (i.e. interfaces). The other methods, wait(), notify(), finalize(), etc. are sufficiently complicated and/or are native, so it's best they're already implemented, and would not benefit from being abstracted.
So I'd guess the answer would be no, none of the methods of Object would benefit from being abstract.
Would it be a benefit to mark the Object class as abstract?
Assuming all the methods are implemented, the only effect of marking Object abstract is that it cannot be constructed (i.e. new Object() is a compile error). Would this have a benefit? I'm of the opinion that the term "object" is itself abstract (can you find anything around you which can be totally described as "an object"?), so it would fit with the object-oriented paradigm. It is however, on the purist side. It could be argued that forcing developers to pick a name for any concrete subclass, even empty ones, will result in code which better expresses their intent. I think, to be totally correct in terms of the paradigm, Object should be marked abstract, but when it comes down to it, there's no real benefit, it's a matter of design preference (pragmatism vs. purity).
Is the practice of using a plain Object for synchronisation a good enough reason for it to be concrete?
Many of the other answers talk about constructing a plain object to use in the synchronized() operation. While this may have been a common and accepted practice, I don't believe it would be a good enough reason to prevent Object being abstract if the designers wanted it to be. Other answers have mentioned how we would have to declare a single, empty subclass of Object any time we wanted to synchronise on a certain object, but this doesn't stand up - an empty subclass could have been provided in the SDK (java.lang.Lock or whatever), which could be constructed any time we wanted to synchronise. Doing this would have the added benefit of creating a stronger statement of intent.
Are there any other factors which could have been adversely affected by making Object abstract?
There are several areas, separate from a pure design standpoint, which may have influenced the choice. Unfortunately, I do not know enough about them to expand on them. However, it would not suprise me if any of these had an impact on the decision:
Performance
Security
Simplicity of implementation of the JVM
Could there be other reasons?
It's been mentioned that it may be in relation to reflection. However, reflection was introduced after Object was designed. So whether it affects reflection or not is moot - it's not the reason. The same for generics.
There's also the unforgettable point that java.lang.Object was designed by humans: they may have made a mistake, they may not have considered the question. There is no language without flaws, and this may be one of them, but if it is, it's hardly a big one. And I think I can safely say, without lack of ambition, that I'm very unlikely to be involved in designing a key part of such a widely used technology, especially one that's lasted 15(?) years and still going strong, so this shouldn't be considered a criticism.
Having said that, I would have made it abstract ;-p
Summary
Basically, as far as I see it, the answer to both questions "Why is java.lang.Object concrete?" or (if it were so) "Why is java.lang.Object abstract?" is... "Why not?".
Plain instances of java.lang.Object are typically used in locking/syncronization scenarios and that's accepted practice.
Also - what would be the reason for it to be abstract? Because it's not fully functional in its own right as an instance? Could it really do with some abstract members? Don't think so. So the argument for making it abstract in the first place is non-existent. So it isn't.
Take the classic hierarchy of animals, where you have an abstract class Animal, the reasoning to make the Animal class abstract is because an instance of Animal is effectively an 'invalid' -by lack of a better word- animal (even if all its methods provide a base implementation). With Object, that is simply not the case. There is no overwhelming case to make it abstract in the first place.
From everything I've read, it seems that Object does not need to be concrete, and in fact should have been abstract.
Not only is there no need for it to be concrete, but after some more reading I am convinced that Object not being abstract is in conflict with the basic inheritance model - we should not be allowing abstract subclasses of a concrete class, since subclasses should only add functionality.
Clearly this is not the case in Java, where we have abstract subclasses of Object.
I can think of several cases where instances of Object are useful:
Locking and synchronization, like you and other commenters mention. It is probably a code smell, but I have seen Object instances used this way all the time.
As Null Objects, because equals will always return false, except on the instance itself.
In test code, especially when testing collection classes. Sometimes it's easiest to fill a collection or array with dummy objects rather than nulls.
As the base instance for anonymous classes. For example:
Object o = new Object() {...code here...}
I think it probably should have been declared abstract, but once it is done and released it is very hard to undo without causing a lot of pain - see Java Language Spec 13.4.1:
"If a class that was not abstract is changed to be declared abstract, then preexisting binaries that attempt to create new instances of that class will throw either an InstantiationError at link time, or (if a reflective method is used) an InstantiationException at run time; such a change is therefore not recommended for widely distributed classes."
From time to time you need a plain Object that has no state of its own. Although such objects seem useless at first sight, they still have utility since each one has different identity. Tnis is useful in several scenarios, most important of which is locking: You want to coordinate two threads. In Java you do that by using an object that will be used as a lock. The object need not have any state its mere existence is enough for it to become a lock:
class MyThread extends Thread {
private Object lock;
public MyThread(Object l) { lock = l; }
public void run() {
doSomething();
synchronized(lock) {
doSomethingElse();
}
}
}
Object lock = new Object();
new MyThread(lock).start();
new MyThread(lock).start();
In this example we used a lock to prevent the two threads from concurrently executing doSomethingElse()
If Object were abstract and we needed a lock we'd have to subclass it without adding any method nor fields just so that we can instantiate lock.
Coming to think about it, here's a dual question to yours: Suppose Object were abstract, will it define any abstract methods? I guess the answer is No. In such circumstances there is not much value to defining the class as abstract.
I don't understand why most seem to believe that making a fully functional class, which implements all of its methods in a use full way abstract would be a good idea.
I would rather ask why make it abstract? Does it do something it shouldn't? is it missing some functionality it should have? Both those questions can be answered with no, it is a fully working class on its own, making it abstract just leads to people implementing empty classes.
public class UseableObject extends AbstractObject{}
UseableObject inherits from abstract Object and surprise it can be implemented, it does not add any functionality and its only reason to exist is to allow access to the methods exposed by Object.
Also I have to disagree with the use in "poor" synchronisation. Using private Objects to synchronize access is safer than using synchronize(this) and safer as well as easier to use than the Lock classes from java util concurrent.
Seems to me there's a simple question of practicality here. Making a class abstract takes away the programmer's ability to do something, namely, to instantiate it. There is nothing you can do with an abstract class that you cannot do with a concrete class. (Well, you can declare abstract functions in it, but in this case we have no need to have abstract functions.) So by making it concrete, you make it more flexible.
Of course if there was some active harm that was done by making it concrete, that "flexibility" would be a drawback. But I can't think of any active harm done by making Object instantiable. (Is "instantiable" a word? Whatever.) We could debate whether any given use that someone has made of a raw Object instance is a good idea. But even if you could convince me that every use that I have ever seen of a raw Object instance was a bad idea, that still wouldn't prove that there might not be good uses out there. So if it doesn't hurt anything, and it might help, even if we can't think of a way that it would actually help at the moment, why prohibit it?
I think all of the answers so far forget what it was like with Java 1.0. In Java 1.0, you could not make an anonymous class, so if you just wanted an object for some purpose (synchronization or a null placeholder) you would have to go declare a class for that purpose, and then a whole bunch of code would have these extra classes for this purpose. Much more straight forward to just allow direct instantiation of Object.
Sure, if you were designing Java today you might say that everyone should do:
Object NULL_OBJECT = new Object(){};
But that was not an option in 1.0.
I suspect the designers did not know in which way people may use an Object may be used in the future, and therefore didn't want to limit programmers by enforcing them to create an additional class where not necessary, eg for things like mutexes, keys etc.
It also means that it can be instantiated in an array. In the pre-1.5 days, this would allow you to have generic data structures. This could still be true on some platforms (I'm thinking J2ME, but I'm not sure)
Reasons why Object needs to be concrete.
reflection
see Object.getClass()
generic use (pre Java 5)
comparison/output
see Object.toString(), Object.equals(), Object.hashCode(), etc.
syncronization
see Object.wait(), Object.notify(), etc.
Even though a couple of areas have been replaced/deprecated, there was still a need for a concrete parent class to provide these features to every Java class.
The Object class is used in reflection so code can call methods on instances of indeterminate type, i.e. 'Object.class.getDeclaredMethods()'. If Object were to be Abstract then code that wanted to participate would have to implement all abstract methods before client code could use reflection on them.
According to Sun, An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. This also means you can't call methods or access public fields of an abstract class.
Example of an abstract root class:
abstract public class AbstractBaseClass
{
public Class clazz;
public AbstractBaseClass(Class clazz)
{
super();
this.clazz = clazz;
}
}
A child of our AbstractBaseClass:
public class ReflectedClass extends AbstractBaseClass
{
public ReflectedClass()
{
super(this);
}
public static void main(String[] args)
{
ReflectedClass me = new ReflectedClass();
}
}
This will not compile because it's invalid to reference 'this' in a constructor unless its to call another constructor in the same class. I can get it to compile if I change it to:
public ReflectedClass()
{
super(ReflectedClass.class);
}
but that only works because ReflectedClass has a parent ("Object") which is 1) concrete and 2) has a field to store the type for its children.
A example more typical of reflection would be in a non-static member function:
public void foo()
{
Class localClass = AbstractBaseClass.clazz;
}
This fails unless you change the field 'clazz' to be static. For the class field of Object this wouldn't work because it is supposed to be instance specific. It would make no sense for Object to have a static class field.
Now, I did try the following change and it works but is a bit misleading. It still requires the base class to be extended to work.
public void genericPrint(AbstractBaseClass c)
{
Class localClass = c.clazz;
System.out.println("Class is: " + localClass);
}
public static void main(String[] args)
{
ReflectedClass me = new ReflectedClass();
ReflectedClass meTwo = new ReflectedClass();
me.genericPrint(meTwo);
}
Pre-Java5 generics (like with arrays) would have been impossible
Object[] array = new Object[100];
array[0] = me;
array[1] = meTwo;
Instances need to be constructed to serve as placeholders until the actual objects are received.
I suspect the short answer is that the collection classes lost type information in the days before Java generics. If a collection is not generic, then it must return a concrete Object (and be downcast at runtime to whatever type it was previously).
Since making a concrete class into an abstract class would break binary compatibility (as noted upthread), the concrete Object class was kept. I would like to point out that in no case was it created for the sole purpose of sychronization; dummy classes work just as well.
The design flaw is not including generics from the beginning. A lot of design criticism is aimed at that decision and its consequences. [oh, and the array subtyping rule.]
Its not abstract because whenever we create a new class it extends Object class then if it was abstract you need to implement all the methods of Object class which is overhead... There are already methods implemented in that class...

Categories