Object vs Reference in Java - java

In Java, if I declare,
MyClass obj;
Is obj called a "reference" or an "object". I am not instantiating class here.

obj is a Reference to an instance of MyClass.
Currently, that Reference is NULL because you haven't assigned it to refer to any instance.
Technically MyClass must be a subclass of Object, so it is possible to say that obj is a Reference to an instance of Object as well.

Reference: A variable that points to some object in memory.
It is stored in stack they can be contained in other objects (then they are not really variables, but fields), which puts them on the heap also.
Object: An instance of class that is created dynamically.
It is stored in heap
Example:
MyClassI aObj,aObj1;
aObj=new MyClass2();
At first line aObj and aObj1 are references
At second line aObj referencing to object of MyClass2(New operator creates an object of Myclass2 and its address is assigned to aObj).
To understand even better consider a class Car which has driverName as a member.
Car c1,c2;
c1.driverName="Andrew"
c2.driverName="Gabriel"
System.out.println(c1.driverName);//gives Andrew
System.out.println(c2.driverName);//gives Gabriel
c1=c2;
c2=null;
// gives gabriel because the address of c2 is copied to reference c1.
// the object is not nullified because c2 is just a reference when
// assigning null the address that is stored on c2 in nullified not
// the object it points..
system.out.println(c1.driverName);

In computer science, a reference is a
value that enables a program to
indirectly access a particular data
item, such as a variable or a record,
in the computer's memory or in some
other storage device. The reference is
said to refer to the data item, and
accessing that data is called
dereferencing the reference.
In computer science, an object is any
entity that can be manipulated by the
commands of a programming language,
such as a value, variable, function,
or data structure. (With the later
introduction of object-oriented
programming the same word, "object",
refers to a particular instance of a
class)
so obj is a reference and new MyClass() can be seen as an object

obj is a Reference of type MyClass. The current reference does not point to anything (ie: null).

Sometimes you'll hear people say "Design an method that takes an object as a parameter and..."
If you're new to programming, and especially with Java, such statements can lead to some confusion. These people are using the word "object" to refer to an instance of a class in very general OOP terms, not necessarily Java specific.
When we're talking specifics about Java and the code you have there, it is a reference to an instance of MyClass, which is NULL.

'obj' is a variable. It holds either a reference or null. If it holds a reference, that refers to an object.

In Java, all objects are accessed by reference, and you never have direct access to the object itself.
reference :- is a variable that has a name and can be used to access the contents of an object, A reference can be assigned to another reference passed to a method, or returned from a method. All references are the same size, no matter what their type is Like "Object object ;".
object:- is an entity that's exists in memory allocated by the Java run time environment, An object sits on the heap and does not have a name Like "Object object=new Object();".
so MyClass obj Here is A reference referred to Null.
We can summarize this principle with the following two rules:
The type of the object determines which properties exist within the object in memory.
The type of the reference to the object determines which methods and variables are accessible to the Java program.

The reference is a variable that has a name and can be used to access the contents of an object. A reference can be assigned to another reference, passed to a method, or returned from a method.
All references are the same size, no matter what their type is.
An object sits on the heap and does not have a name. Therefore, you have no way to access an object except through a reference. Objects come in all different shapes and sizes and consume varying amounts of memory. An object cannot be assigned to another object, nor can an object be passed to a method or returned from a method. It is the object that gets garbage collected, not its reference.

Related

Initialize one object to another in java [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 10 months ago.
What happens when I initialize one object to another in java? Is the reference of that object copied in new object or is a new object created with same member values as in the orginal object;
A obj1=new A("apple");
A obj2=obj1;
What is the correct interpretation for this scenario?
when I initialize one object to another in java
I do not know what you mean by "to another". But you initialized only a single object.
First line
Regarding your first line:
A obj1=new A("apple");
A obj1 declares a reference variable, giving it a name obj1, and specifies that this var will hold a reference to any object of type A. This reference variable is initially null.
Calling new A("apple") constructs an object some place in memory. The result, the return value, of this code is a reference to the new object.
The = assigns that reference to be the content of the variable named obj1.
You can think of a reference variable as containing the address in memory where the beginning of that object's block of allocated memory resides. In Java we never see the literal contents of a reference variable. But we know we can reach the object via that reference variable.
In our daily work of programming in Java, we may generally think of obj1 as being the object. But actually obj1 is a way to find the object, a tether attached to the object, a line we can follow to access the object somewhere else in memory.
Second line
Regarding your second line:
A obj2=obj1;
First you declare a new variable named obj2 to hold a reference to an object of type A. Then you copied the reference from obj1 and put that copy into obj2.
You are left with:
A single object.
Two references to that single object.
It is just the reference coppied, not an actual new object in some other memory space.
Normally for deep-copy you can declare yourself a clone method in that class that uses the properties of the passed object and creates another object with new keyword and returns it. This way you will have a new object when you use clone method. More specifically you can declare your class to implement Cloneable interface and then provide an override implementation for the method clone() which already exists in parent Object class.
For shallow-copy you should again create a clone method in your class and in this method you can just use return super.clone() so that the default clone() method provided by Object class will be used to make a shallow-copy of the object meaning only primitive fields will be actually copied and for any non primitive fields the reference will be copied instead.
For your simple example where the field in this class is only some String you can use the shallow copy of clone already provided by Object class and this will seem enough.
If however you had more non primitive fields in this class, then you will had to override your clone method and provide some implementation so that a deep copy could be returned.

Object without reference

I've been practicing component based design pattern and I was wondering if when you initialize an variable without reference meaning initialized as null, Java go ahead and attribute a space in memory that has the size of the variable even though it is set to null so that eventually when you need to reinitialize it with a new instance of a class it just copies the fields of the new instance?
A variable whose type is a reference type occupies the same amount of space whether it contains null or a reference to an object.
However, the variable only holds the reference ... not the object itself.
... when you need to reinitialize it with a new instance of a class it just copies the fields of the new instance?
Erm ... no. When you later "initialize" the variable, you are assigning a reference to the variable. You are not copying the fields of the object.
For example:
SomeType s = null; // the declaration sets aside space for one
// reference, and the initialization assigns
// `null` to it.
s = new SomeType(...) // the 'new' expression creates the object and
// which allocates the space, etcetera
// the assignment merely assigns the reference
// for that object to 's'.
What if "s" is an array of "Sometype" instead still initialized to null, will it be legit to assume that only space for one reference will be saved until you create a new valid reference for an array of the relevant type?
An array type is also a reference type. So, yes, the answer is the same. A declaration SomeType[] s would reserve space for one reference.
I was wondering if when you initialize an variable without reference meaning initialized as null, Java go ahead and attribute a space in memory that has the size of the variable even though it is set to null
Yes memory is allocated for the variable, but this is only a tiny address space bit of memory and nothing else. No memory is allocated for the eventual object.
so that eventually when you need to reinitialize it with a new instance of a class it just copies the fields of the new instance?
When you create an instance of anything, then memory is allocated on the heap for the object, and this happens whether or not the object is assigned to a variable, to no variables, or to 50 variables, and any variable that refers to the object has its address space pointing at the object's location on the heap (perhaps -- I don't think that the actual mechanics, the hows, are fully specified)
Have a look at oracle documentation page regarding objectcreation
Point originOne;
If you declare originOne like this, its value will be undetermined until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object.
For that, you need to use the new operator, as described in the next section. You must assign an object to originOne before you use it in your code.
Instantiating a Class
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:
Point originOne = new Point(23, 94);
I hope above picture clarifies your queries.
The size of reference will be 4 bytes or 8 bytes. Have a look at this SE question:
How big is an object reference in Java and precisely what information does it contain?

Memory reservation for java objects

I know that when declaring object instances in c++ like so:
Object object
the Object constructor is called and memory is provided for that object, however i find that when you do this in java the object instance doesn't have a value until:
object = new Object()
is written. I want to know specifically when memory is provided for the object. I thought that both construction and the new keyword allocated memory so Object object = new Object() seems redundant. I read on oracle's site that declaration "reserves" memory and new "allocates" memory, I would like to know what is the difference between the two.
You need to differentiate between the space required for the variable and the space required for the object. Bear in mind that the value of the variable is just a reference - very much like a pointer in C++. So if you have:
Object x = null;
then the variable x itself takes up enough space for a reference (usually 4 or 8 bytes). Now if you have:
x = new Object();
that creates an object - the value of x is now a reference to the newly created object. x itself takes up the same amount of space as before, but there's also the space required for the object itself (basically the fields, a reference for the type of the object, and data for synchronization and house-keeping).
When you do something like
Object object = new Object()
in Java, object is a reference to the actual instance on the managed heap. Compared to C++, that's roughly doing
Object* object=new Object()
So when you do
Object object;
in Java, a place is created for the 'reference' to a instance.
Similar to
Object* object;
in C++.
Object foo=null;
in meaning of C++ creates reference foo to the object of class Object. So, it consumes memory for reference only.
Object realFoo=new Object();
creates such reference and also real object with whatever is with this object. So, it is memory for the reference and object itself.
In Java there is no memory reservation - only memory allocation.
declaration reserves memory: parameters and variables inside a method will have memory reserved for them in the stackframe.
allocates memory: at runtime, when executing "new", memory will be allocated for the new Object on the heap
It's important to understand that in Java, Object object is simply a reference to an Object called object. If you're familiar with C++, you can think of this reference as a pointer (though it's not quite the same).
On a 64-bit machine, the object reference is 8 bytes. When you actually instantiate an Object using the new keyword and assign it to the reference, this is where memory is allocated for your Object.

Can you say an object is a reference to a class?

As part of my AP class I am learning objects, instances, references etc... So from what I understand a reference is a variable that points to something: a value, class etc . . . Therefore is it legal to say that a object is a reference to a class?
Note: I know this is subjective but I cant seem to find such a comparison anywhere else.
By the usual definition of reference you can not say that. Correct would be "An object is an instance of a class.".
The usual definition of a reference is a value which points to a memory location that is usually occupied by some object. The difference between pointers and references is that you can do pointer arithmetics on the former but not on the latter.
For example in the following code snippet:
SomeClass o = new SomeClass();
SomeClass foo = o;
SomeClass is the class and o is a reference to the instance of SomeClass returned by this particular invocation of the new keyword. new SomeClass() allocates memory for a new instance of SomeClass and calls its constructor to initialize it. foo is another reference to the very same instance of SomeClass also referred to by o. In other words, o and foo point to the same object but are not the same reference.
Object is not a reference of class, but instance of class.
No, that would not be a valid statement. An object is an instance of a class, not a reference to one. When you have something like:
MyClass var = new MyClass();
Then var is a reference to the MyClass instance to which it was assigned (new MyClass()). This instance is in turn an object.
From JLS ยง4.3.1:
An object is a class instance or an array.
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
As somebody else said, a class is a like a blueprint. When you create an object based off of the class, the computer "builds" an object by allocating memory to create "parts" (variables) based off of your class.
Therefore, the object is not a reference to the class, implying that the object simply redirects you to the class.
The object is a instance of the class.
No. That would be like saying that the scrambeled eggs you ate this morning are a reference to the abstract concept of scrambeled eggs.
Remember that a class is a blueprint, but it's not an actual, concrete object on its own. That only happens when you instantiate an object via the new keyword.
An object is really an instance of a class. Let's say we have the String class. An object of the type String is an instance of the String class, not that class itself. Given String s="foo", s's value would be a reference to an instance of the String class.
Now, every class has a java.lang.Class object that is associated with it, so String.class is a reference to an instance of java.lang.Class.
From JLS:
An object is a class instance or an array.
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
Object foo = new Object();
foo is an reference to a specific, concrete instance of the class Object but not to the class itself.
Class bar = Object.class;
bar is a reference to the Object class.

Java reference storage question

In java, when you pass an object to a method as a parameter, it is actually passing a reference, or a pointer, to that object because objects in Java are references.
Inside the function, it has a pointer to that object which is a location in memory. I am wondering where this pointer lives in memory? Is a new memory location created once inside the function to hold this reference?
Within a function, a parameter reference is stored on the stack. The thing-referenced can live anywhere.
When some code calls a method, what normally happens is that space is made on the executing thread's stack, and this space is used to hold the parameters that are passed to the function. If one of the parameters "is an object", what's really in play is a reference to an object; that reference is copied onto the stack so that the called code can find it. It's important to recognize that the object itself is not copied, just the reference.
The prologue section of the called code will then typically allocate more space on the stack, for the method's own local variables, but underneath, the JVM has a pointer to the stack frame with all the parameters, so the called code can locate the object named by the parameter. Items created with 'new' will be allocated from the heap, and can persist even after the method exits, but all items allocated on the stack are dumped simply by moving the stack pointer back to where it was before the call.
Objects are not references, but you use references everywhere. e.g.
String a = "abc";
the a is a reference to a String. So references get passed around everywhere. Are they pointers ? No. A reference is more like a handle to an object. The JVM is at liberty to move around objects within memory. A pointer would have to change to reflect this. A reference doesn't. A reference could be modelled as a pointer to a pointer.
Every parameter of the function is passed by value - however, the parameter is not an object, but instead is a reference.
So the same object exists with two references to it.
String s = "my string"; // reference to this object created
doSomething(s); // in the doSomething function, a new reference to the same point of memory is passed by value
This means when I have my function void doSomething(String str) I work the same way as I do outside the function, except I have a different reference. Same object being referenced, but different reference. So if inside my function I do str = "different string"; that won't change s - s still points to the same point of memory it did the whole time - but now str instead of pointing to what s points to, now points to where the "different string" is stored.
for example in JFrame you can start like this:
public myFrame mF;
public void Panel1(myFrame mF) { your code ... }

Categories