1

This question already asked before but I don't find good understandable answer from there. I would actually want to know that unlike c++ class objects can't be created statically in java why ? and what are the main disadvantages to create objects statically that java designers want to prevent to be occur ?

Thanks.

Community
  • 1
  • 1
Vikas Verma
  • 3,626
  • 6
  • 27
  • 40
  • primitive types (int, char..) etc are created on stack (statically) in java – Rakib Jun 12 '14 at 08:16
  • 1
    @Rakibul I don't think primitives are objects ... . Objects are created using 'new' keyword in Java. – Kasper Ziemianek Jun 12 '14 at 08:19
  • @xwid, why not? in pure OOP *everything* is object. In Ruby even numbers are objects. – Rakib Jun 12 '14 at 08:22
  • 5
    @RakibulHasan Java is not pure-OOP my friend... – earthmover Jun 12 '14 at 08:23
  • 2
    @AnkitLambda Whatever 'pure OOP' means. Is anything pure OOP? – user207421 Jun 12 '14 at 08:37
  • @rukibul a language to be "pure oo" everything should exists as objects, but int, float, char, .. etc are not objects in Java. – Vikas Verma Jun 12 '14 at 08:42
  • @EJP If you want a pure OO language, try Smalltalk. Everything is an object in Smalltalk. This is not the case for Java, where primitive types (int, float) aren't objects by themselves. – Vikas Verma Jun 12 '14 at 08:44
  • I guess one if the reasons is to allow runtime polymorphism to work without too heavy a syntax (although [I still don't see a good reason for the use of `new` everywhere](http://stackoverflow.com/questions/6340535/is-the-new-keyword-in-java-redundant)). – juanchopanza Jun 12 '14 at 08:44
  • @EJP - http://stackoverflow.com/questions/12836522/java-is-pure-object-oriented-or-not , http://stackoverflow.com/questions/974583/is-java-100-object-oriented – TheLostMind Jun 12 '14 at 08:45
  • Logically, _if_ you want everything to be an object, then everything should be an object (e.g. as in Python). Java does treat a few types specially, I think initially for performance reasons. – James Kanze Jun 12 '14 at 08:46
  • 1
    @VikasVerma I didn't say I wanted a pure OOP language. I don't, because I don't know what it is, or why I would want one, or why it would be desirable in the first place. Instead, I expressed doubt as to whether there is such a thing, and as to whether there is an accepted definition. I've never seen one, and it don't consider yours to be adequate. – user207421 Jun 12 '14 at 08:48
  • @TheLostMind I've seen all those questions. The the answers seem to mostly agree with me. – user207421 Jun 12 '14 at 08:49
  • I'm not sure what all the OOP holy-war comments are even doing here they don't really seem to address the question. – Matt Coubrough Jun 12 '14 at 08:56
  • Java was originally designed to be *familiar* (ie similar syntax to C++) but *simple* (removing common sources of errors that arise when using a language like C++). There is excellent info from Oracle about these goals here that go some way to answering the question: http://www.oracle.com/technetwork/java/simple-142339.html – Matt Coubrough Jun 12 '14 at 09:03
  • @MattCoubrough It was also designed to be safe and fast.... –  Jun 12 '14 at 09:07
  • @Poldie Yes other good reasons why all Objects are dynamically allocated in Java. The article series I linked to explains it all far better than I could summarize in a Stack Overflow answer especially in a closed thread. Hopefully the original poster reads it to get a better understanding of the "Whys" – Matt Coubrough Jun 12 '14 at 09:11
  • 1
    @MattCoubrough I am re-opening because the "duplicate" was closed for other reasons, and does not have any good answers. So you should be able to add an answer now. – juanchopanza Jun 12 '14 at 09:28

2 Answers2

4

Good question. One is tempted to say that it is because the authors of the language knew better than you what value types you need, and provided them, and didn't want to let you define new ones (e.g. like Complex). And there's certainly some of that: it also explains the lack of operator overloading.

But I suspect that that wasn't the reason in the minds of the Java authors. You need dynamic allocation and pointers (what Java calls references) in some cases, such as when polymorphism is involved, and the Java authors simply decided that they would only support this idiom, rather than making the language more complex by having it support several different idioms. It's a pain, of course, when you actually need value semantics, but with care, you can simulate them (java.lang.String would be a good example) by making the class final and immutable, with "operators" which return a new instance.

Of course, the added expressiveness of C++ does give more possibility for errors: it's easy to take the address of a local variable, for example, and end up with a dangling pointer. But just because you can do something doesn't mean that you have to; in C++, an incompetent programmer can make the program crash immediately, where as in Java, he'll generally end up with a wrong result (although uncaught exceptions aren't that rare either).

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • So there is no advantage to create objects statically over dynamically except its a small overhead to create objects dynamically than statically. And Most TADS games define a large number of "static" objects that encode the game world: the locations, characters, and items that make up the game. We call these objects "static" because they exist throughout the program's execution. So here is also a good reason to create objects statically. – Vikas Verma Jun 12 '14 at 08:55
  • @VikasVerma You have to be careful when using words such as "statically" in this context. It sounds like you are talking about static objects, which I guess you aren't. – juanchopanza Jun 12 '14 at 08:57
  • @juanchopanza Yes I am talking about static obects – Vikas Verma Jun 12 '14 at 09:01
  • @VikasVerma I really don't think so, because you *can* create static objects in Java. – juanchopanza Jun 12 '14 at 09:13
  • @juanchopanza u meant that we can create static class object ? if yes then can you show me a small code snippet. – Vikas Verma Jun 12 '14 at 09:23
  • @juanchopanza No you can't. All objects must be dynamically allocated in Java. (In Java, basic types like `int` aren't objects.) – James Kanze Jun 12 '14 at 10:54
  • 2
    @JamesKanze Java allows you to make static instances of any type. Whether the object is allocated "dynamically" or not is a different matter. Based on comments I think OP is confusing static allocation with automatic storage. – juanchopanza Jun 12 '14 at 12:14
2

Edit: It appears the poster may actually be asking why can't Objects be static in Java?, in which case, the answer is "they can" and I have added that to the answer at the bottom. If however the question is why can't Objects be allocated on the stack as they can in C++ then the first part of this answer attempts to deal with that:


I guess it boils down to the design goals of the Java language.

Because java has a garbage collector it doesn't really need to have stack allocated objects.

Trying to make things simpler, safer, familiar, while keeping them fast and consistent were design goals of the Java language designers.

Quoting from here http://www.oracle.com/technetwork/java/simple-142339.html (emphasis is mine):

Simplicity is one of Java's overriding design goals. Simplicity and removal of many "features" of dubious worth from its C and C++ ancestors keep Java relatively small and reduce the programmer's burden in producing reliable applications. To this end, Java design team examined many aspects of the "modern" C and C++ languages to determine features that could be eliminated in the context of modern object-oriented programming.

One of those features that the designers decided was of "dubious worth" (or unnecessarily complicated the language or its Garbage Collection processes) were stack-allocated Objects.

These online chapters cover the design goals of the Java language in-depth.


Reviewing the comments I believe that I may have misinterpretted the original poster's question because the question seems to be confusing the two completely orthogonal concepts of allocating Objects on the stack with statically allocated Objects.

  • Stack allocation refers to value Objects that exist only within their current scope and occupy space on the stack.

  • Static allocation refers to instances that exist per Class - Objects that can exist for the lifetime of the application and are initialized within a static allocation block.

Java doesn't support the former concept (except with primitive data types) for the reasons explained above; but it certainly does support the latter. It is perfectly acceptable Java code to instantiate a static Object belonging to a class. A very simple example of a static Class Object would be this snippet of code:

public class Foo {

    public static Integer integerValue = new Integer(32);

}

This would create a single public instance of an Integer Object that belongs to the class Foo. Because it is public in this example, one could access it and set it by calling:

Foo.integerValue = 57;

Note that only one (effectively global) copy exists of the integerValue regardless of how many Foo instances are instantiated.

A common use of statics is for class constants (declared with the the final modifier), but static variables in Java do not have to be constant: they are mutable by default if you omit the final modifier. Static variables need to be used with caution in multi-threaded applications, but that's another story.

For more information on static variables in java, you can read about them here:

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

and here:

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Hopefully the helps.

Matt Coubrough
  • 3,739
  • 2
  • 26
  • 40
  • can you explain this statement more briefly "Because java has a garbage collector it doesn't really need to have stack allocated objects." – Vikas Verma Jun 12 '14 at 09:44
  • I'm trying to say that by letting the garbage collector take care of ALL Objects, instead of having some Objects that are stack allocated value-objects and some that are dynamically allocated, the language can be made simpler, and making the language simple was one of the core design goals of Java. – Matt Coubrough Jun 12 '14 at 09:47
  • but is static objects create any hitch in java's goal ? – Vikas Verma Jun 12 '14 at 09:56
  • @VikasVerma static objects are a single instance. This is a completely orthogonal concept. – juanchopanza Jun 12 '14 at 09:57
  • @VikasVerma But lets say that it is quite hard to implement runtime polymorphism à la Java without dynamic allocation, because you don't know the size of the objects you will be instantiating until runtime. – juanchopanza Jun 12 '14 at 09:59
  • @juanchopanza Yeah to implement run-time polymorphism we need dynamically allocation but I don't think so that is a good reason to remove static object concept from java. As I said in most TADS games define a large number of "static" objects that encode the game world: the locations, characters, and items that make up the game. We call these objects "static" because they exist throughout the program's execution. So it is a good reason to create static objects. – Vikas Verma Jun 12 '14 at 10:06
  • 1
    The language may be simpler, but at the cost of making the code to implement real applications more complicated, and often less reliable. (When you leave scope in C++, you call destructors. There is no way in Java to ensure that unreachable objects have been correctly "destructed".) – James Kanze Jun 12 '14 at 10:56
  • 1
    Except that they didn't completely decide that static allocated objects were of dubious worth, because the made a few built-in value types. If they were consistent, `int` and `double` would also be objects, with functions like `add` which returned a new object. What actually has occurred is that the authors of Java have decided for us once and for all what types should be value types, and what types not; we don't get to create new value types. – James Kanze Jun 12 '14 at 10:59
  • @James kanze - I'm not arguing that they achieved their aims! I'm just giving the "why" they did it. In my experience more people struggle to learn C++ than Java which means at some level they must've made the language simpler. I'm also specifically referring to Objects not primitive types, and yes they could have made it even simpler by abandoning primitives too, and making everything an Object, but presumably that would have prevented them reaching their other goal of making it fast enough to be useful. – Matt Coubrough Jun 12 '14 at 20:54
  • @Vikas Verma, I've edited my answer to try and address confusion - **Static** allocation is possible in Java, so I have edited my answer to try and make that clear. – Matt Coubrough Jun 12 '14 at 23:38
  • @MattCoubrough Thanks matt you address my half confusion but I also want to know that what are the reasons that we can't allocate Objects on the stack like C++. Hope you help me to address this problem. – Vikas Verma Jun 13 '14 at 08:51