Saturday, December 1, 2012

12/1/12 How objects really work

A long time ago, I discussed Objects and Instance variables. As you may or may not remember, an Object is not like a primitive data type, but more like a collection of primitive variables that can also be manipulated by the Object. To create an object, you would type:

(Object name) (name) = new (Object name)((parameters));

This code will simply create a (Object name) with the name (name), and starting values (parameters) for the variables in the object that you are creating. Now, what would happen if I tried the following code without a toString method in (Object name)?

System.out.println((name));

Well, you should get something weird like Obj@1cd2e6f. You may then be wondering "what dose this mean?", well it is telling you where in your computers memory you are storing (name). This means that (name) is not actually a (Object name), but a pointer saying where in the memory to look for (name). This may not seem like it makes that much of a difference, but it dose. Let's take the following code:

Object a = new Object(1,"hi");
Object b = new Object(1,"hi");
if(a==b){
 return true;
}
else{
 return false;
}

It seems that this code should return true because the two objects are the exact same, but it dose not. It fails to do so because this code is simply checking if a has the same memory address as b doses. If you want to see if two objects are equal, you will need to create a equals method for that object. This has one other implication, what do you think will be the output of this code:

Person a = new Person("Bob");
Person b = new Person("Joe");
b=a
a.setName("Smith");
System.out.println(b.getName());

It should be Bob, but remember that the name a or b is simply pointing to the object that it is representing, meaning that when you are saying that b = a you mean that b is now pointing to the same place in memory as a is. This means that both person a and b are the same person, and both have the name Smith, so the output would be Smith.

Hopefully you have learned a thing or two about Objects and how they work in Java

No comments:

Post a Comment