• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between Reference Data Types & Own Objects  RSS feed

 
craig morgan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to understand the difference between a reference data type and an object in terms of passing values. What I am struggling with is the fact that reference data types, such as a String are actually Objects. Why is it then that if I do this...



...then String a becomes "Dog" and String B remains "Cat".
However, if I create a Cat Class with a private String speak with getter and setter methods and do this...


...then B effectively references A which means and both return the same value ("Meaow").

If I then set both A & B hold the value = "Meaow Meaow".

So the question is - Why does my own Object operate differently to a String Object (or other reference type)?

Thanks!
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This has nothing to do with the objects, but how you are using them.

In the string case, you are changing one of the references to point to a different object. In the second case, you are changing the object itself -- and since the two references point to the same object, they should both change.

Henry
 
Dan Patterson
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cat A = new Cat();
Cat B = A; <= This line is not creating a new object, it is making "B" a refernece to the already created object that Variable A is pointing to.

Cat A and B are reference variables that are referencing the same object which is created in the new Cat() line.
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First example

changes the variable a (reference) not the String object itself (which cannot be changed). b will still reference to the old String.

Second example

changes the Cat object not the variable A.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your String example would be equivalent to



If you use that code, you get exactly the same behaviour as in the String example.

You can't change the String example to make it work like your first Cat example, simply because String is immutable - it doesn't have any getters. In contrast, StringBuffer has, and could be used to show the same behaviour.
 
craig morgan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ilja - finally a reply which makes sense!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!