Because an object hast state and behavior - unlike a primitive.
And objects need to be created, which you do with the word new. imagine it like a call to a special method which returns a fresh instance of that object.
JDBCSupport - An easy to use, light-weight JDBC framework -
annamalai bala wrote:
Im new to java can any one please tell me the difference?
object reference variable
cat c=new cat();
why can't we just declare it as cat c? what does new cat() means here.
"new Cat()" is what creates the actual object on the heap. "Cat c" is where you declare the reference to that object. That statement creates Cat object in the heap and assigns it to the "c" reference which you can use to manipulate the object (reference is like a remote control to a TV which you can use to control it). When it comes to primitive variables they are the "value holders".
Well,variables comes in two flavors, primitive and Object reference.
Primitive variables contains fundamental values, like int, float, boolean etc, where "Object reference" contains/refers the handle of the Object that has been created using the "new <ObjectName()>" syntex.
Here int i = 10; means ==> 'i' is the name of the primitive variable, whose data type is integer (means it can hold integer type values) and currently it is holding its value as 10.
and cat c=new cat(); this line can be written in another way as,
Cat c ;
c = new Cat();
Where c is the reference of the 'object', that has been created using "new Cat()", and where Cat() is the user defined class.
With 'new Cat()', you are creating object and allocating memory to the class Cat() and after creating the object, you can refer/access the "Cat object", with the reference/handle 'c'.
“Men are only as good as their technical development allows them to be.”
I just realized something myself while reading through this thread. The separation of the reference variable declaration
and the instance creation and assignment
c = new Cat();
makes more sense when you consider being able to do something like
Animal c = new Cat();
Animal d = new Dog();
subject: Difference between Object reference variable and primitive variable