d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Java, Confused About References Vs Objects.
Add Reply New Topic New Poll
Member
Posts: 31,293
Joined: Mar 25 2009
Gold: 0.00
Dec 14 2018 09:43pm
So i kind of understand what they are, and kind of not....


Person steve = new Person();
^that is creating an object of "steve" from class Person.



BUT, at the same time, "steve" is not an object, it's a reference in memory to the object?
This is kind of confusing to me, it makes sense that "steve" is an object... but it's also a reference? idk....
Member
Posts: 3,664
Joined: May 31 2007
Gold: 6,762.00
Dec 15 2018 02:38am
In C++ you can operate either on object, or a pointer to the object.

In Java, you do not have that choice.
Type variables (line int) are never a pointer.
Class variables are always a pointer.

In your example, you written 2 operations in a single line.
What happens here:
Person steve = null; // this is creating a pointer
steve = new Person(); // this is creating new object of class "Person", and assign it to your pointer.
Member
Posts: 3,664
Joined: May 31 2007
Gold: 6,762.00
Dec 15 2018 02:44am
Another example:

String x = null; // creating pointer to string

x = "A"; // creating an object containing "A"

x = "B";
// what java language will do:
// 1) create string object "B"
// 2) assign string object "B" to pointer variable "x"
// 3) Garbage collector will later remove string object "A", that stil exists in memory, but is not assigned to any pointer.
Member
Posts: 8,992
Joined: Mar 24 2013
Gold: 18,115.00
Dec 16 2018 09:36am
Also, whener the new keyword is used, we are talking about reference. So, for example:

Foo foo = new Foo();

You are assigning new reference to foo object.
Member
Posts: 12,703
Joined: May 17 2013
Gold: 12,935.00
Dec 16 2018 03:16pm
Quote (pzold @ 16 Dec 2018 16:36)
Also, whener the new keyword is used, we are talking about reference. So, for example:

Foo foo = new Foo();

You are assigning new reference to foo object.


Creating a new Foo object is not really a great example to use.

References are hidden from sight in Java, and the only time you have to think about the notion of a "reference" is when assigning an already existing object to a new variable.
Member
Posts: 17,651
Joined: May 22 2009
Gold: 0.00
Jan 27 2019 08:32pm
Steve is a reference that references a New Person() that is currently residing within the Heap.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll