Initialize one object to another in java [duplicate] - java

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.

Related

Java LinkedList.get() does not return deep copy? [duplicate]

This question already has answers here:
Java: recommended solution for deep cloning/copying an instance
(10 answers)
Closed 8 years ago.
I have a question about using a LinkedList and the .get() operation. Java as I understand passes objects by reference, so if I have a linked list called A, and I do temp B = A.get(i), I retrieve an object B that I can modify and the changes are reflected in A.get(i).
However, if the object B has within it (Say another LinkedList object), I do not get a deep copy correct? Is the solution that I must create a copy constructor for my class 'temp' in this example. Or is there a better, built-in way to do this?
Thanks for your help.
Java as I understand passes objects by reference..
No. Java pass everything by value. If you have a reference type, the reference is passed by value. See this question.
if I have a linked list called A, and I do temp B = A.get(i), I retrieve an object B that I can modify and the changes are reflected in A.get(i).
If you have a list of reference types get(i) will return a reference to a particular instance. The element in the list and your retrieved reference will refer to the same object. So if you change the object in some way, it will be "visible" from both references.
However, if the object B has within it (Say another LinkedList object), I do not get a deep copy correct?
Correct. You get a reference.
Is the solution that I must create a copy constructor for my class 'temp' in this example. Or is there a better, built-in way to do this?
If you need a deep copy of your object, you must implement it yourself.
Java as I understand passes objects by reference
No. It passes references by value. It doesn't pass objects at all [except in the case of RMI.]
so if I have a linked list called A, and I do temp B = A.get(i), I retrieve an object B
No. You retrieve a reference that refers to B. The same B whose reference you passed when you added it to the list.
that I can modify and the changes are reflected in A.get(i).
Yes, see above.
However, if the object B has within it (Say another LinkedList object), I do not get a deep copy correct?
Correct. Just like the first case. No difference whatsoever.
Is the solution that I must create a copy constructor for my class 'temp' in this example.
Solution to what? I've never used a copy constructor or the clone() method in Java since 1997. What problem are you trying to solve?
Or is there a better, built-in way to do this?
To do what?
It does not return a "deep copy" because there is no copying done at all, at least, not at the object level. Let me explain.
When you have an instance of an object, the variable that references that object is a pointer to the object. The object can be referenced and modified by many variables (pointers). Observe the following code:
// Let's assume I have a custom object class called Student
// Here the object is created and s now points to the new Student object
Student s = new Student();
// Here I create another variable that points to the same object
Student s2 = s;
Those two variables both point to the same object and any changes that one variable makes to the object will then be reflected in the other.
This ties into your list example. If you have a LinkedList of objects, it is actually a list of pointers to objects. So calling get(2) on the list will get a reference to the 3rd object in the list. The object that it's referencing is the object, not a copy. So any references, variables, methods etc. that were in this object will still be there.
I hope that answers your question :)

Clarity needed on cloning: Shallow copying of objects is NOT just assigning object reference variable to another variable or is it? [duplicate]

This question already has answers here:
How do I copy an object in Java?
(23 answers)
Deep copy, shallow copy, clone
(4 answers)
Closed 8 years ago.
I asked a question about cloning in java and got answers saying deep copy creates a new instance of the object carrying the same state and data in the member variables. I was told shallow copying is just assigning an object reference to another reference variable. But that's NOT copying that's assignment (making a new pointer for the object location).
What is deep copying of objects then really if there are reference variables contained within the object you are trying to clone? Would using myObj2 = myObj.clone() clone all components within the object? Lets say if myObj contained other reference variables pointing to other object locations, would those reference variables also be cloned? So myObj2's internal reference variables would not be pointing to the same old object locations that pointers in myObj where pointing to.. I need clarity here to fully understand what cloning is all about.
Thank you in advance.
I can give you an unsatisfying answer: the "clarity needed" will not be available. :)
The problem is, here are the first two sentences of the documentation for java.lang.Object.clone():
Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. (emphasis added)
So it's up to the author of the class.
If you read the further documentation on clone(), it suggests that it should implement a deep copy (that copies all objects by value, rather than reference). For example:
Typically, this means copying any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing the references to these objects with references to the copies.
But the default implementation of clone() does not do this:
Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.
So it depends on the class, and how the author interpreted the above semantics (assuming the author understood them).

How does the special variable "this" know exactly which Object to refer to in a program in JAVA? [duplicate]

This question already has answers here:
Using the keyword "this" in java [duplicate]
(12 answers)
Closed 9 years ago.
If the special variable this refers to an Object in a variable/method that is being used. How does it know exactly which object it must refer to out of various objects in a program?
The mechanism is almost disappointingly simple.
Each instance method actually takes one more argument than you declare for it, and that extra argument is assigned to this. Java syntax just thinly disguises this. When you write
list.get(0);
you have actually written
get(list, 0);
in a slightly modified way. The Java runtime resolves which get method to call by inspecting the type of that first argument and locating the appropriate get method in its class.
this points to the current object instance that it is used in.
If you define a class A with a method() that contains a this reference then you create two instances of the class
A a1 = new A();
A a2 = new A();
If you call a1.method() then this will refer to a1, if you call a2.method() then this will refer to a2
A a = new A();
a.doSomething(i) // is same as calling doSomething(a, i).
So, internally this refers to "a". The first argument to the function will be the object (there will only be one method that will be used by all objects). So, argument o will be the current object which has called this function.
From JAVA LANGUAGE SPECIFICATION
The keyword this may be used only in the body of an instance method,
instance initializer, or constructor, or in the initializer of an
instance variable of a class. If it appears anywhere else, a
compile-time error occurs.
When used as a primary expression, the keyword this denotes a value
that is a reference to the object for which the instance method was
invoked (§15.12), or to the object being constructed.
The type of this is the class C within which the keyword this occurs.
At run time, the class of the actual object referred to may be the
class C or any subclass of C.
The keyword this is also used in a special explicit constructor
invocation statement, which can appear at the beginning of a
constructor body (§8.8.7).
You can also refer to Oracle Tutorials
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
Oracle Java Tutorials
this is a very important keyword that can differentiate between parent and child class objects. this refers to the present context in which object has too be referred to..!!

Java, passing variables/objects into a function [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 years ago.
I'm interested to know exactly what's happening under the bonnet when passing a variable or object into a function.
When passing an object or variable into a function, is a new copy of the object/variable created in the new scope? (A set of parentheses constitutes a scope in java right?). Or is the reference to the existing variable/object in memory passed in? Although that would only make sense for a global object/variable?
java is always pass by value so a new variable or reference variable(which refer to some object) will be created in the function to receive the value that has passed to it...
The scope of these variable will be withing that function in which it has created.
One thing you should know that even object are passed by value in java...when people say we pass the object to method ,that time we actually pass the value referred by reference variable not the object...so both the old and new reference variable refer to same object in heap memory..
check this for reference...
http://javadude.com/articles/passbyvalue.htm
http://www.programmerinterview.com/index.php/java-questions/does-java-pass-by-reference-or-by-value/
The easiest way to think of this is to get away from thinking of variables as ever being objects. A reference variable or expression is either null or a pointer to an object of appropriate class for its type.
Under this model, all Java argument passing is by value.
When you pass a reference to a method, you pass the null-or-pointer value to it. Assignment to the argument only affects the argument. It does not affect any variables in the caller's environment. On the other hand, if it is not null it points to the same object as the caller's variable or expression pointed to. Calling a value-changing method in that object changes its value for all code using a pointer to that object, including the caller.
Both - you get a copy of the object reference (for objects), and a copy of the value for primitives.
So unlike C, you can't pass in a variable reference (for a string for example) and end up with it being repointed to something else. And you can't pass in an int, for example, and change it's value within the method - any changes it to it will only be within the method scope.
e.g:
MyObjectHolder holder = new MyObjectHolder();
holder.setObject(new Object());
//holder reference id = 1
// holder.object reference id = 2
doIt(holder);
public void doIt(MyObjectHolder methodScopeHolder) {
// methodScpeHolder reference id = 3
// methodScopeHolder.object reference id = 2
}
In Java your program's "local" variables are maintained in a "stack frame", which is a section of a large array whose elements can contain any data type.
When you call, you copy the parameters (which may be either "scalars" -- chars, ints, floats, etc -- or "references") into a new area of the array (the "top"). Then, during the call, the index values that control which elements of the array you can access are adjusted, and the copied parameters become the "bottom" of a new stack frame, with the called method's local variables being above parameters. So to the new method its copies of the parameters are just like local variables.
Effectively, each method has a "window" into the overall stack, and the "windows" overlap to cover the parameter list.
Of course, when you "pass" an object you're really just passing a reference to the object, and the object itself is not copied.
When you pass a variable, you are passing the reference.
When you pass an object, you are passing a copy of it.

Object vs Reference in 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.

Categories