Re: Objects in java
On Sat, 04 Jul 2009 05:51:09 -0700, Prasoon <prasoonthegreat@gmail.com>
wrote:
At run time,
the literal integer constant 5, whose size was known at compile time...
So while creating objects (using new) is the size of an object known
at compile time or it is also decide at run time...
In C++ new is used to create objects (allocate memory) at run-time and
that even holds for primitive data types but in java everytime the
memory is allocated at run time (for objects as well for primitive
data types) so why is "new" needed in JAVA???
Because that's how the language works.
Your statement about C++ isn't actually correct anyway. A primitive data
type would be, for example, an "int". Even in C/C++ the only time memory
can be allocated is at run-time, and you can't explicitly allocate storage
for a primitive data type simply by using the type itself. Just as in
Java, a primitive data type has to exist inside some other context where
storage is allocated implicitly (e.g. global variable, local variable,
class or struct member, etc). In C/C++, you can't write code like this:
void a()
{
int i = new int();
}
Just as with Java, storage for "i" is already allocated implicitly as a
local variable. There's no need to use the "new" operator in that case,
nor could you even if you wanted to. The C/C++ compiler has to be more
explicit about the size of the storage, because it's operating at a lower
level of abstraction than Java. But in both cases, it's known at compile
time that there needs to be storage for that local variable of a primitive
type.
In C/C++ you might do something like this:
void a()
{
int *pi = (int *)malloc(sizeof(int));
*pi = 5;
}
Or even something like this:
class A
{
private:
int _i;
public:
A(int i) : _i(i) { }
int getI() { return _i; }
void setI(int i) { _i = i; }
}
void b()
{
A a = new A(5);
}
But those examples both have, very roughly speaking, an equivalent in Java
too:
void b()
{
Integer i = new Integer(5);
}
In other words, the semantics of primitives in Java are practically the
same as that of primitives in C/C++. It's only when you get into
reference types (i.e. classes) that significant differences start
appearing, and even there the main difference is one of explicitness,
rather than some fundamental difference in operation (one obvious
exception being, of course, that in C/C++ you can implicitly allocate a
class or struct as a local variable just as you can a primitive, whereas
in Java classes always have to be allocated explicitly...that critical
difference allows Java to not concern itself with pointer types at all).
Pete