Вопрос-ответ

What is the difference between a variable, object, and reference? [duplicate]

В чем разница между переменной, объектом и ссылкой?

В чем именно разница между переменными, объектами и ссылками?

Например: все они указывают на некоторый тип, и все они должны содержать значения (если, конечно, у вас нет временного типа с возможностью сохранения null), но чем именно их функции и реализации отличаются друг от друга?

Пример:

Dog myDog = new Dog(); //variable myDog that holds a reference to object Dog
int x = 12; //variable x that hold a value of 12

У них одинаковые концепции, но чем они отличаются?

Переведено автоматически
Ответ 1

(Просто для ясности, объяснение, которое я даю здесь, специфично для Java и C #. Не думайте, что оно применимо к другим языкам, хотя некоторые его фрагменты могут быть.)

Мне нравится использовать аналогию с сообщением кому-либо, где я живу. Я мог бы написать свой адрес на листе бумаги.:


  • Переменная подобна листу бумаги. Она содержит значение, но сама по себе значением не является. Вы можете вычеркнуть все, что там есть, и написать вместо этого что-нибудь другое.

  • Адрес, который я пишу на листе бумаги, похож на ссылку. Это не мой дом, но это способ навигации к моему дому.

  • Мой дом сам по себе похож на объект. Я могу выдавать несколько ссылок на один и тот же объект, но есть только один объект.

Помогает ли это?

Разница между типом значения и ссылочным типом заключается в том, что записывается на листе бумаги. Например, здесь:

int x = 12;

это все равно, что иметь лист бумаги с цифрой 12, написанной непосредственно на нем. Тогда как:

Dog myDog = new Dog();

само содержимое объекта Dog не записывается на листе бумаги - оно создает новое Dog , а затем записывает ссылку на dog на этом листе бумаги.

В терминах , отличных от аналогии:


  • Переменная представляет место хранения в памяти. У нее есть имя, по которому вы можете ссылаться на нее во время компиляции, а во время выполнения у нее есть значение, которое всегда будет совместимо с ее типом во время компиляции. (Например, если у вас есть Button переменная, значение всегда будет ссылкой на объект типа Button или некоторый подкласс - или на null ссылку.)

  • Объект - это своего рода отдельная сущность. Важно отметить, что значение переменной или любого выражения никогда не является объектом, только ссылкой. Объект фактически состоит из:

    • Поля (состояние)

    • Ссылка на тип (никогда не может изменяться в течение срока службы объекта)

    • Монитор (для синхронизации)


  • Ссылка - это значение, используемое для доступа к объекту, например, для вызова методов на нем, доступа к полям и т.д. Обычно вы перемещаетесь по ссылке с помощью . оператора. Например, если foo это Person переменная, foo.getAddress().getLength() примет значение foo (ссылка) и вызовет getAddress() объект, на который ссылается эта ссылка. Результатом может быть String ссылка... затем мы вызываем getLength() объект, на который ссылается эта ссылка.

Ответ 2

Я часто использую следующую аналогию при объяснении этих концепций.


Представьте, что объект - это воздушный шар. Переменная - это person. Каждый person находится либо в команде типа значения, либо в команде ссылочного типа. И все они играют в небольшую игру со следующими правилами:

Правила для типов значений:


  • You hold in your arms a balloon filled with air. (Value type variables store the object.)

  • You must always be holding exactly one balloon. (Value types are not nullable.)

  • When someone else wants your balloon, they can blow up their own identical one, and hold that in their arms. (In value types, the object is copied.)

  • Two people can't hold the same balloon. (Value types are not shared.)

  • If you want to hold a different balloon, you have to pop the one you're already holding and grab another. (A value type object is destroyed when replaced.)

Rules for reference types:


  • You may hold a piece of string that leads to a balloon filled with helium. (Reference type variables store a reference to the object.)

  • You are allowed to hold one piece of string, or no piece of string at all. (Reference type variables are nullable.)

  • When someone else wants your balloon, they can get their own piece of string and tie it to the same balloon as you have. (In reference types, the reference is copied.)

  • Multiple people can hold pieces of string that all lead to the same balloon. (Reference type objects can be shared.)

  • As long as there is at least one person still holding the string to a particular balloon, the balloon is safe. (A reference type object is alive as long as it is reachable.)

  • For any particular balloon, if everyone eventually lets go of it, then that balloon flies away and nobody can reach it anymore. (A reference type object may become unreachable at some point.)

  • At some later point before the game ends, a lost balloon may pop by itself due to atmospheric pressure. (Unreachable objects are eligible for garbage collection, which is non-deterministic.)

Ответ 3

You can think of it like a answering questions.

An object is a what...

It's like any physical thing in the world, a "thing" which is recognizable by itself and has significant properties that distinguishes from other "thing".
Like you know a dog is a dog because it barks, move its tail and go after a ball if you throw it.


A variable is a which...

Like if you watch your own hands. Each one is a hand itself. They have fingers, nails and bones within the skin but you know one is your left hand and the other the right one.
That is to say, you can have two "things" of the same type/kind but every one could be different in it's own way, can have different values.

A reference is a where...

If you look at two houses in a street, although they're have their own facade, you can get to each one by their one unique address, meaning, if you're far away like three blocks far or in another country, you could tell the address of the house cause they'll still be there where you left them, even if you cannot point them directly.

Now for programming's sake, examples in a C++ way

class Person{...}
Person Ana = new Person(); //An object is an instance of a class(normally)

That is to say, Ana is a person, but she has unique properties that distinguishes her from another person.

&Ana //This is a reference to Ana, that is to say, a "where" does the variable 
//"Ana" is stored, wether or not you know it's value(s)

Ana itself is the variable for storing the properties of the person named "Ana"

Ответ 4

Jon's answer is great for approaching it from analogy. If a more concrete wording is useful for you, I can pitch in.

Let's start with a variable. A variable is a [named] thing which contains a value. For instance, int x = 3 defines a variable named x, which contains the integer 3. If I then follow it up with an assignment, x=4, x now contains the integer 4. The key thing is that we didn't replace the variable. We don't have a new "variable x whose value is now 4," we merely replaced the value of x with a new value.

Now let's move to objects. Objects are useful because often you need one "thing" to be referenced from many places. For example, if you have a document open in an editor and want to send it to the printer, it'd be nice to only have one document, referenced both by the editor and the printer. That'd save you having to copy it more times than you might want.

However, because you don't want to copy it more than once, we can't just put an object in a variable. Variables hold onto a value, so if two variables held onto an object, they'd have to make two copies, one for each variable. References are the go-between that resolves this. References are small, easily copied values which can be stored in variables.

So, in code, when you type Dog dog = new Dog(), the new operator creates a new Dog Object, and returns a Reference to that object, so that it can be assigned to a variable. The assignment then gives dog the value of a Reference to your newly created Object.

java c#