"Object" vs "Object Variable" in Java? - java

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();

Related

How JVM treats reference variables?

Just want to know whether this statement is true or not:
For these lines of code:
Person Bob = new Person("Bob W.", 30);
System.out.println(Bob.name);
An Object Person is created and its memory address or a kind of reference is sent to Bob, the reference variable . Next, when we call "Bob.name", the JVM looks at the "address" held by Bob and goes there to look at the Person Object. Then JVM looks at Bob's name and prints it!
Thanks!
All objects in Java are accessed via their references (different from primitive access!). The variable bob is a reference to an instance of the Person class. Memory allocation/disposal of instances will be handled by the JVM, and the instance data will be kept alive by the JVM as long as there exist strong references to that instance (ie Person bob = new ... declares a strong reference to the newly created Person instance).
An Object Person is created and its memory address or a kind of reference is sent to Bob, the reference variable
It would be more correct to say that an "An instance of the Person Object is created", but yes, all variables used for objects in Java are reference variables. Calling new will return the reference to the instance created. There can be many reference variables which point to a single instance. For example, in the following code snippet we can have two references pointing to a single instance:
Person bob = new Person("Bob W.", 30);
Person bob2 = bob;
Next, when we call "Bob.name", the JVM looks at the "address" held by Bob and goes there to look at the Person Object.
Exactly. After code is compiled, the JVM bytecode will use the instruction getfield to access the name field. This instruction requires an object reference and the field reference. In this case bob.name will use bob as the objectref and use Person#name as the fieldref.

How is an object created in Java? To be specific, What is the process going on in the memory when an object is created?

Please help me clear this confusion its bugging me alot. When I write the following code what happens in the memory and how is the object Jhon stored?(If I am correct that Jhon is an object and not merely a reference to an object)
class Human{
String Name;
float height;
}
class Student extends Human{
int Student_ID;
Student Jhon = new Student();
}
My question is, is Jhon an object or is it a reference to an object created? what is the reference variable here? What is an object variable here?
I'd say this is well-explained by the following line from JLS:
The value of a class instance creation expression is a reference to the newly created object of the specified class.
So, in the following code:
Student Jhon = new Student();
^-----------^ Class instance creation expression
^----------^ Variable declaration
To reiterate: the value of the class instance creation expression is the reference to a newly created object. That object is created somewhere in memory; but the key point is that the value isn't that object, but a reference to it.
And then you assign that reference to a variable, Jhon. So Jhon is not an object, nor a reference, but a variable whose value is a reference to a variable.
Just to add to #Andy Turner's response. Jhon is a variable that points to the reference to an instance of the class student that is held in the Java Virtual Machine (JVM) memory heap. The programmer has no way of directly accessing the object in the heap, that is all done by the JVM. The heap is managed by the JVM, when an object in the heap no longer has a variable that points to the reference to it, it will be cleaned up by the JVM garbage collection. The programmer does not have to concern themselves with this process.
See more detailed explanantion in official Oracle docs
Also see helpful disccusion in opening chapter of David Eck's book

In java, is an object considered a variable?

One source I am studying defines an array as "a collection of variables under one name, where the variables are accessed by index numbers."
But then I realized that you can have an array of objects (or an array of pointers to objects, at least).
This got me to wonder what a variable is defined as in java, as I did not consider an object to be a variable. Jenkov Tutorials cites a variable as being "a piece of memory that can contain a data value."
And since I believe an object fits this definition, is an object considered a variable?
Calling an array a "collection of variables" is arguably stretching the definition already. But an array is certainly a collection of references that can be made to point to different objects in memory, and each such reference can reasonably be called a variable.
Asking "is an object a variable" is a little weird in the first place. In Object o = new Object(), o is clearly a variable, though remember it's a reference to an object in the heap, not the object itself.
Honestly, "variable" is a pretty flexible, ill-defined term -- is a field a variable? The return result of a method? It depends on who's talking and what fuzzy definition they're using today.
is an object considered a variable?
No, these are two distinct things.
The first one (the object) is the value and the second one (the variable) is a way to reference an object, generally to use it (invoking a series of method on it for example).
For example when you write :
new Dog()
You instantiate a Dog. Nice. But suppose you want feed it if it is hungry.
You cannot if you have not a way to chain a series of method on this object.
By storing the reference of the Dog in a dog variable you can do it :
Dog dog = new Dog();
if (dog.isHungry()){
dog.feed();
}
Jenkov Tutorials cites a variable as being "a piece of memory that
can contain a data value."
It says the same thing.
But this :
One source I am studying defines an array as "a collection of
variables under one name, where the variables are accessed by index
numbers."
is rather misleading.
An array is an object that has a state that contains, among other things, elements of the array.
The way which the elements are referenced in is a implementation detail of the Array class and I would not affirm that each element is stored in a specific variable.
An object is created when you call the constructor with the reserved word new.
For example:
Object a = new Object();
a will be the variable of that new object created and will go to reserved memory for that object. You are instantiating that new variable and that variable is associated with that object.
Hope might this will help you to understand it better...
class Bulb
{
private int w;
public void setWattage(int e)
{
w=e;
}
public int getWattage()
{
return w;
}
}
class Test
{
public static void main(String args[])
{
Bulb b[];
b=new Bulb[2];
b[0]=new Bulb();
b[1]=new Bulb();
b[0].setWattage(60);
b[1].setWattage(100);
System.out.println(b[0].getWattage());
}
}
here b[0] and b[1] are reference variables who have the address of two Bulb objects

Java object creation difference

I'm new to OOP concepts in Java. What is the difference between these two incidents?
1.
ClassName obj_name = new ClassName();
obj_name.method();
2.
new ClassName().method();
A good explanation is much appreciated. Thanks
In Option(1), you are still having/holding the reference to the object, so you can reuse that reference to access/call the other members(method/variables) of the object (class).
In Option (2), you don't have the reference (i.e., reference has been lost), so you will NOT be able to use it again.
One point to remember is that if you want to access the same object members multiple times, you need to hold the reference (use option 1 above), rather than creating the object (option 2) again and again (which is costly operation i.e., occupies memory).
Please refer the below link for more details:
https://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html
The reference variable obj_name hold the object of ClassName.through which you can call the instance method of ClassName through reference variable obj_name.
Whene ever we create an object and dont assign its reference to any reference variable its Known as Anonymous object instantiation.The Advantage of this type of instantiation is that you can only do the limited operation on that.Like you can call a single method.
If you want to perform mopre operation then reference varaibale which hold the object is better approach.If you have multiple method in your class and you want to use them then option 1 is right choice.
for details please go through this Link
While they might accomplish the same objective for the first call, the two approaches do fundamentally different things in terms of class definition and instantiation.
ClassName object = new ClassName();`
object.method();`
This is a case of instantiation. You create a new ClassName object which possesses certain instance fields and methods. It can call these methods, and the result may cause its instance fields to change.
ClassName.method();
On the other hand, this approach does not create an instance of the class. Instead, it calls method as a class attribute. Thus, the result can change fields in ClassName, but it won't necessarily existing fields in already-instantiated objects.
public class ClassName(){
public int attr = 0;
public ClassName(){}
public void setAttr(int value){
this.attr = value;
}
public void method(int value){
this.attr += value;
}
}
Now, using the first approach, we can create a newObj and call newObj.method(100). This will increase newObj's instance variable attr by 100.
To see the difference between the two approaches, let's use setAttr(200) to change the object's attr to 200.
Next, if we just use ClassName.method(100), the class's attr value will become 100 for all future instances of ClassName. So if we create ClassName nextObj = new ClassName(), this new instance of ClassName will have attr of 100, while newObj will still have attr of 200.
Hopefully this explains the core difference between the two approaches.
in option 1 you are creating an object with new keyword
followed by constructor and that object is referenced by class_name
obj_name variable so obj_name is pointing to that object.
In option 2 you not referencing to that object. just you make an
object and call the method with no references so that object is
eligible for garbage collection.

Subtleties of Inheritance

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).

Categories

Resources