I am looking to clarify my knowledge of java:
basketball o, s;
s = new basketball();
o = s;
The question is how many basketball objects are created, 1 or 2? I ran some tests and thought only 1 object was created, as when I modified one, it was reflected in the other. Sorry for the simple question, I was just seeking to clarify this.
only one object is created but 2 referrences are created.Here(basketball o, s;) o and s are just references
But when you did s = new basketball(); then an object is created
and after that when you did o=s then you are just pointing to s but not creating any object
Have a look at this to see different ways of creating objects
Only one object is created here. o and s are just handles to the same object and, as you said yourself, modifying one will modify the other (as they're pointing to the same object).
To understand more clearly, I'd recommend reading How is a Java reference different from a C pointer? and Is Java “pass-by-reference” or “pass-by-value”?
s is the only object created then o references/points to the location of s in memory.
your variables o and s are just references, when you use the operator new AnyObject() then you create your object and it return the reference pointer to whaterver the left hand side varaible.
so you have 2 references and 1 object
and both reference variables point to that object
Since you seem new to java i will explain in detail,
When you write this basketball o, s; in java , it means you are creating two reference variables of type basketball. What a reference variable means is , it is a type of variable that can point to the actual object of basketball.
When you write this s = new basketball(); in java it means, You are creating a new object in java , and assigning that object to the reference variable. This means you are providing a link to the object through s
Imagine this, the reference variable as a remote control and the object (instance variable) as a TV. Although all the real work is done by TV , the control of entire TV is done through the remote control. Its a link to the TV for the user.
so When you do o = s; , you are assigning the object (instance variable) pointed by s to o . Hence now both s and o point to the same object. And hence When changes are made on one it obviously will reflect on the other. Imagine it like having two remote controls for the same TV.
For your answer , Only one object is created , but two references are created.
basketball o, s;
s = new basketball();//Here you create the object after that
o = s;//here you assign the address of 1st object(which is store in s) to o
suppose s = new basketball();
lets take the address of s is 23490.After that we put this address value into o.So o is also pointing the same object.
Hence one object will be created.
Related
UPDATE
public Fish mate(Fish other){
if (this.health > 0 && other.health > 0 && this.closeEnough(other)){
int babySize = (((this.size + other.size) /2));
int babyHealth = (((this.health + other.health) /2));
double babyX = (((this.x + other.x) /2.0));
double babyY = (((this.y + other.y) /2.0));
new Fish (babySize, babyHealth, babyX, babyY);
}
return null;
}
When new Fish is called, is there a new instance of Fish floating around somewhere without a reference or have I just allocated memory for a new Fish without actually instantiating it?
Can I get the new Fish call to create an actual instance of the Fish with a unique reference name other than iterating through a loop?
When new Fish is called, is there a new instance of Fish floating around somewhere without a variable name or have I just allocated memory for a new Fish without actually instantiating it?
A new Fish object will be created, and will be garbage-collected since there is no reference to it.
The garbage collection will take place (sometime) after the constructor of Fish is done.
In your case that doesn't make much sense, but sometimes it does, if instantiating an object will start a new Thread or run some other routines that you want to be run only once.
If I have only allocated memory or there is a Fish without a name, how can I get the new Fish call to create an actual instance of the Fish with a unique variable name?
This is not very clear. But I sense that you just want to return new Fish(...); and assign it to a variable yourself where you call it, something like:
Fish babyFish = femaleFish.mate(maleFish);
"have I just allocated memory for a new Fish without actually instantiating it?"
No. The instance is initialized (the constructor is executed), but if no reference is kept for this instance it will eventually be garbage collected. Keep in mind that a reference can be kept even if your code doesn't do so, for example if the constructor puts this in some static variable.
The following figure's explanation really helped me when I had confusion in the beginning and I hope will help you as well.You can think of Employee as Fish here.
In your case you created a new Fish() object locally inside a method, so the lifetime of that should be assigned locally as well.The garbage collector always looks for unused objects and will identify this suitable for collection as soon as your method exits,along with other locals defined inside the method.
You are returning null, so this method can not be treated as factory method structure since it does not return an instance.I am not sure what you mean by :
Can I get the new Fish call to create an actual instance of the Fish with a unique reference name other than iterating through a loop?
But I think you asked if you can use the exact new Fish() that is inside the method.The short answer is: no. Although you can definitely create another new Fish() but you need a reference variable to retrieve that address or you can return the instance for the method instead of null,which will be a static factory method and is known as a good practice when you want to separately name your constructors.
In a more specific manner to answer both of your updated questions:
1)You did created a new object when you wrote new Fish() but you did not create a reference variable to really retrieve that object information.It's like you have built a house but you don't know the address of the house.Then you can never get to the house. What will happen is because of the lack of retrieval process, this object will be identified as unused by the garbage collector and hence it will be collected.
2)Since there is no reference/pointer or anything to get the information stored in the new object, you cannot retrieve the exact new Fish() inside the method but you can certainly create another object with a reference variable if you really wish to retrieve the information stored in the object.
Lastly, although it is mainly written for C language usage, the following document by Nick Parlante of Stanford University does an exceptional job in explaining references, stack,and heap memories.Click here.
First, let me clear up some confusion in your terminology: An object doesn't have a name. A variable has a name, but you can have many variables of different names all referring to the same object. Having a named variable reference the object does not mean the object has a name.
If you do new Fish() but don't assign the new reference to anything, the new object will be unreachable as soon as the constructor returns.
There is no way to recover that reference, and the object will be unallocated by the next Garbage Collection run.
Let's say SList is a super class of TailList.
If I execute the following codes,
SList s;
TailList t = new TailList();
s = t;
is this same as doing SList s = new TailList();?
Now, is static type of t still TailList?
When you execute SList s = new TailList();, what happens is the following:
new TailList() is invoked, creating a new object which the constructor of TailList is run for. When the constructor finishes, an anonymous TailList reference is returned.
The anonymous TailList reference is assigned to s.
Since a TailList is inheriting from SList, you can also refer to it by that. The reference to the object doesn't change the object itself.
Imagine I put a trash bin somewhere, and then tell someone who doesn't know of that object being a trash bin that I put a "container" at that location. The trash bin is indeed a container, but that person only knows that it's a container. This doesn't change the fact that it's a trash bin, but the other person can't safely assume that he can put trash in there, or that it is scheduled to be emptied at any time, therefore he wouldn't know to invoke this functionality on the "container" that he is refering to.
So for instance, let's say we have the following code:
String s = "Hello there";
Object o = s;
o is now refering to a String object, but is treating it as an "object", it doesn't know that it has a length, or that it contains characters, even though it does.
s on the other hand, while still refering to the same object that o is refering to, knows that this object is a String, and can use String functionality on that object.
If we wanted to, we could assume that o is a String by a mechanism called "casting":
String s2 = (String)o;
We now refer to the object referenced by o as a String. All of this changes nothing for the object itself, it's all a mere change in reference. As if, for the previous analogy, the person who was told about the mysterious "container", will assume that the container is more specifically a "trash bin". We could also make a wrong assumption, that the container is a packaging container
Integer i = (Integer)o; // throws ClassCastException
Fortunately, when we assume wrongly in Java, we get a ClassCastException, unlike in real life where if you put your items into a trash bin while refering to it as a packaging container your belongings will be thrown to garbage.
Or perhaps, what is confusing you is that first assignment. Well, new TailList() part of SList s = new TailList(); by itself is a static invocation of the constructor of TailList, and it will always return a TailList reference. The assignment that comes afterwards will still refer to the TailList object that was constructed by the invocation.
TL;DR
Yes, it's the same thing.
The object will be instantiated as TailList, and the assignment won't change that. (It would be a neat trick if the language could change the implementation class on assignment ;) )
For example, you can always go
TailList t = new TailList();
Object o = t;
Does that make it more clear? The object is still the same implementation class. It' not going to change to an Object, even though we're referencing it that way.
You could always do a System.err.println(s.getClass().getName()) and see.
BTW this is actually polymorphism rather than inheritance, because you're referencing the object as a class higher in the hierarchy. Inheritance would be if you called t.slistMethod() without overriding it.
In statically typed object-oriented languages, both objects and variables have an associated type.
The type of a variable (the 'static type') is specified by the programmer when declaring the variable. It never changes.
The type of the object referenced by the variable (the 'runtime type') must be either the same or a subtype of the variable's declared type. An object never changes type, but the variable may be assigned a different object of a different type.
The first snippet declares two variables, s of type SList and t of type TailList. It creates an object of type TailList and stores a reference to it in both variables.
The second snippet declares a variable s of type SList, creates an object of type TailList, and stores a reference to it in s.
The end result in both cases is that s contains a reference to an object of type TailList. The difference is that in the first snippet there is an additional reference to the object stored in variable t (which still has a static type of TailList).
Is
TailList t = new TailList();
SList s = t;
The same as
SList s = new TailList();
Yes, except there's no separate reference of type TailList held to the new object, so you'll only be able to access methods from SList (unless you cast).
In the following image, p points to person.
p is passed as a reference to a function named callFunction. Now,if I make any change in p will they also get reflected in person ? Please explain.
I understand that argument passed is the reference value of the original variable (I hope so !). But I can't think further.
If you change the details of p as such, it'll get reflected
// Nothing done to p before this
p.changeName("Not Sanika Anymore"); // This will be reflected as both point to the same object as references are the same
If you create a new Person and assign it to p then it wont
// New Person for p
p = new Person("New Sanika"); // now this p is pointing to the newly created object's reference
p.changeName("Not Sanika Anymore"); // This won't be reflected
That is because java is purely pass-by-value. You are passing the reference of the object as a value to callFunction().
This answer by Eng.Fouad explains this concept in a really good way.
Yes, because both reference are pointing to same Person object. When you change some attribute using any reference, same object will be updated.
As long as you change the members of the object which is pointed by the reference p , They'll get reflected , As java passes parameter by value .
What is Pass by value ??
The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the run-time stack for the application (which is how Java handles it), but other languages could choose parameter storage differently. So there is no way of the method having contact with the original reference here.
So Pass by reference is implemented differently , this is where actually you can have freedom of playing with reference . Here references can be changed in the method .
I am teaching myself Java, and one of the review exercises in my book asks for the difference between an "object" and an "object variable."
I know what an object is (a specific instance of a class), but I can't seem to find the term "object variable" anywhere in the book (no answers section) or on the internet.
Does anyone know the meaning of this term?
I'll bite.
The Object is the instance itself, whereas the Object Variable is the reference to the Object.
Here's a contrived example:
Object o = new Object();
Object ref1 = o;
In his case, there is a single instance of the Object, but it is referenced by two Object Variables: o and ref1.
When an Object is no longer referenced by an Object Variable, the Object is garbage collected.
It's a synonym of "instance variable":
class A {
static int m; // <-- class variable
int n; // <-- instance variable
...
}
Evidently, this term is not so commonly used, and it would better to avoid any potential ambiguities by just sticking with "instance variable".
tl;dr;fmoe
I came across the same question in a review exercise found within Cay Horstmann, Big Java, Early Objects (John Wiley & Sons, 2013), 73.
Cay defines an object variable as a variable (whose type is a class) which stores a reference to the memory location of an object.
Rectangle box = new Rectangle();
box is the object variable which stores a reference to the newly instantiated Rectangle object's memory location.
Multiple object variables can exist which store the same reference to an object's memory location.
Rectangle box = new Rectangle(5,10,20,30);
Rectangle box2 = box;
Calling a mutator/mutagenic method (modifies the object on which the method is invoked) on either object variable mutates (modifies) the object since the object variables reference the same object's memory location
box2.translate(15, 25);
System.out.println(box.getY()); // 35.0
System.out.println(box2.getY()); // 35.0
This gets a bit confusing if you compare Cay's definition with the information from The Java Tutorials, and numerous other sources, but I believe this is the answer to your question when placed within the context of Cay's book(s).
I prefer this perspective => An object's memory location is stored in the object reference (object variable per Cay). When I invoke a method on an object, I specify the object reference followed by the dot (.) operator, followed by the method name.
objectReference.method();
If the public interface of a class allows access to one or more of it's instantiated object's fields (AKA instance variables, object variables, class member variables, properties, or attributes... depending on programming language and documentation) then I can access it by specifying the object reference, followed by the dot (.) operator, followed by the field name
objectReference.fieldName;
Why do I prefer this? I'm not a fan of using variable as a noun too many times; overloaded semantics boggle my simple mind.
#Faaris Cervon : Object variables are the variables which does not create any object but refer to some object ..
exmp : Date d1= new Date();
d1 is a object.
date d2;
d2 is not an object and neither it refers any object But it can hold any object of type date.
d2=d1; // valid.
hence d2 is a object variable.
It is important to remember that object variables does not contains objects actually but it refers to some object.
I found something that help you too.
There are few words like object, object variable and object reference.
Object variable and object reference are similar in the way that object variable stores the reference of an object where as object reference describes the location of an object. (You might be confused here so just consider them as same)
consider an example::
Class Car{
....
....
}
Car AudiQ7; //S1
Car AudiQ8 = new Car(); //S2
Here in S1 we created only object. Means it does not refer to memory.
In S2 we created an object variable/reference means it refers to memory location.
At university its tought, that an Object Variable is: "a variable whose type is a class, and which holds a reference to an object that is an instance of that class"
Object thing = new Object();
I'm trying to keep my address the same, since I have a JList pointing towards listAccts. How do I make ListAccts have the same address space? Basically, how do I copy this object?
public class BankEngine extends AbstractListModel {
/** holds the accounts inside the bank engine */
private ArrayList<Account> listAccts;
/** holds all the actions the user has done. */
private ArrayList<Action> actions;
/** holds old versions of the bank. */
private ArrayList<ArrayList<Account>> oldEngines;
/*****************************************************************
* Constructor that creates a new BankEngine, the core of the project
******************************************************************/
public BankEngine() {
listAccts = new ArrayList<Account>();
// actions = new ArrayList<Action>();
oldEngines = new ArrayList<ArrayList<Account>>();
oldEngines.add(listAccts);
}
public void undo() {
if (oldEngines.size() == 0) {
} else {
listAccts = oldEngines.get(oldEngines.size()-1); <--- I want this to have the same listAccts pointer.
}
All the objects in a java process share the same address space i.e. the address space of the running JVM
If I understand correctly, you want to ensure that listAccts refers to the same physical object throughout the lifetime of your code. Unless you assign listAccts to refer to a different object (in code you haven't shown us), this is a given.
After oldEngines.add(listAccts) is executed, oldEngines will contain a reference to the same object listAccts is referring to. However, listAccts is not changed in any way - it still refers to the exact same object!
So - again: unless you reassign listAccts in code you haven't shown us - the line
listAccts = oldEngines.get(oldEngines.size()-1);
looks totally unnecessary to me. In fact, it may be confusing you, if you have added other elements to oldEngines in the meantime, as then its last element won't anymore refer to the same object listAccts does.
Note also that Java doesn't have pointers, only references. All non-primitive (object) variables are actually references, not by-value copies of an object. And the JVM can actually change the physical memory location of objects under the hood, updating all references to these objects. We have no way to notice this, because there is no way to get the actual physical memory address from a reference (at least within Java - I guess you could do it using e.g. JNI). A reference is a higher level of abstraction than a pointer - it is not a memory address. This is why terms like address space are meaningless in Java.
Update
what I'm trying to do is make it so that the last oldEngine is now replacing what is the current listAccts.
If you mean to change the listAccts reference to point to the last element in oldEngine, you are already doing that. If you mean to copy the contents of the last element in oldEngine into the current listAccts object (overwriting its current contents), try
listAccts.clear();
listAccts.addAll(oldEngines.get(oldEngines.size()-1));
If you mean you want listAccts to essentially be the same object as it was before, i.e. you don't want to create a new list, then what you need to do is:
listAccts.addAll(oldEngines.get(oldEngines.size() - 1));
i.e., manipulate your existing list rather than creating a new object.
My problem was I was passing along the same old listAccts to the array list, without saying "new". Even when I did say "new" i was passing along the accounts inside of listAccts, so the arraylist would be new, but the accounts inside of the new array list would be the ones I wanted to have backups of. What I had to do was create a new object from a deep copy using this method.
http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2
Thanks everyone who offered help.