Question:
What is the difference between object and a reference variable?
A1-Guy
2013-11-26 13:43:51 UTC
My confusion is in understanding linkedList concepts

In which we first make a Node class
class Node
{
public int iData;
public String sData;
Node next; //Reference variable

////////////////Other methods///////////////

}//End of Node class

In "public class LinkedList class"

Confusion is when we create a Node by using following statement. Lets say:
Node playerList = new Node(10, David Beckham);

//I know this creates an object of Node Class and using "playerList" ref. variable i can call methods/functions of Node class

In LinkedList class we also have first field (datatype: Node) a reference variable(i.e not an object).

public class LinkedList()
{
Node first;
//Since it is a reference variable, not object does it mean it does not have access to Node class method or it does have access to Node class methods.

I hope i am making my question understandable
P.S: Wish there was a way to add snapshots with your question here?
Three answers:
?
2013-11-26 14:15:15 UTC
As long as the Node class methods/variables are dynamic (not static) and public, you can access them:



//inside some method in LinkedList

first = new Node(...);

first.sData = "Messi";

first.someMethod();



The difference between a reference variable and an object is actually quite simple: only the latter can store data, while the former simply points to an object.



Consider this:



Node first = new Node(10, "David Beckham");

Node other = first;

other.iData = 12;

System.out.print( first.iData );



This code will print 12, not 10, because "other" isn't a new node, it's just a new reference variable pointing at the same object as "first". Only the "new" keyword will actually create a new instance / object.

This can be quite confusing at first, but what made it very clear for me is the fact that printing other will result in something like this: [Node@32be2a2

Because "other" is literally just a memory address, pointing at the Node created in the first line.
2013-11-27 04:38:40 UTC
An object is the actual storage space in memory in which some collection of data resides. A reference variable is a variable which refers to the memory location of an object. Look at the pseudocode

below: Object obj = new Object(); Here obj is the reference variable, and the data to which it refers is the object.
adel
2013-11-26 21:51:39 UTC
okay ,, i think i get your question.. it is still an object , even if its a instance variable of another class. so it does have access to its methods.



btw .. you can't put in parameters in the Node class .. unless you have another class declariation in the Node class

e.g.

public Node(int d, string s){

this.iData = d;

this.sData= s;

}



Chris has a more precise explanation


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...