That might have been tricky. The answer should look something like this. There
might be other ways to do it, but I think this is the simplest one. If you
didn't get this, it's okay. There's more practice coming up. There are some
subtletles to how this method works, so let's go through an example. Let's say
we have two variables, one for Maria and one for Jamesha. Each of those should
contain a person object with a name and friends. We have string objects. For
Maria's name, Maria's current friends, Jamesha's name and Jamesha's current
friends. Let's say we call maria.addFriend(jamesha). We call this method on the
maria object and we pass in as an argument the Jamesha object. Now, when this
line runs, the first thing that it does is creates a new string from these
ones. This will be the new string that's created. It's going to put together
friends, friend.name, and a space. Friends is the friends of the maria object
because that's what we called the method on. So, we go to the Maria object, and
friends is currently just TJ, with a space. friend.name is the friend, the
argument, which was the Jamesha object, dot name, which is Jamesha. And the
space is just a space. So, when these strings get put together, it'll look like
TJ Jamesha. Now the string created by this part will be assigned into the
friends variable. So, the old reference will go away and a new one will be
created. And now, Jamesha appears in the friends of Maria. The old friends
string that contained just TJ might still be around. And it hasn't changed, but
the friends variable in the Maria object now contains a reference to a
different string.
Eso pudo ser un poco confuso. La respuesta debería parecerse a esto. Es posible
que haya otras maneras de hacerlo, pero creo que esta es la más simple. Si no obtuvieron
esto, no se preocupen. Hay más práctica más adelante. Hay algunas
sutilezas sobre como funciona este método, así que veamos un ejemplo. Digamos
que tenemos dos variables, una para María y otro para Jamesha. Cada una de las cuales debería
contener un objeto Persona con un nombre y amigos. Tenemos objetos de Cadena para el
nombre de María, sus amigos actuales, el nombre de Jamesha y los amigos
actuales de Jamesha. Digamos que invocamos maria.addFriend(jamesha). Invocamos a este método en el
objeto maria y pasamos como argumento al objeto jamesha. Bien, cuando esta
línea se ejecuta, lo primero que hace es crear una nueva cadena
de éstos. Esta será la nueva cadena que se crea. Va a agrupar
«friends», «friend.name» y un espacio. «Friends» son los amigos del objeto María.
porque en eso es en lo que invocamos el método. Por lo tanto, vamos al objeto María, y
amigos es actualmente solo TJ, con un espacio. «friend.name» es el amigo, el
argumento, que fue el objeto jamesha, punto nombre, que es Jamesha. Y el
espacio es sólo un espacio. Así que, cuando estas cadenas se agrupan, se verá como
TJ espacio Jamesha espacio. Bien, la cadena que creó esta parte se asignará a
la variable «friends». Entonces, la vieja referencia desaparecerá y se creará
una nueva. Y ahora, Jamesha aparece en los amigos de Maria. La cadena vieja de friends
que contenía solo TJ podría aún estar alrededor y no ha cambiado, pero
la variable «friends» en el objeto María ahora contiene una referencia a una
cadena diferente.
C'était peut-être compliqué.
La réponse devrait ressembler à ça.
Il pourrait y avoir d'autre approches
mais je pense que c'est la plus simple.
Si vous n'avez pas compris,
pas grave.
Il y aura d'autres exercices.
Il y a quelques subtilités
autour de cette méthode,
alors regardons un exemple.
Disons que nous avons deux variables,
une pour Maria et une pour Jamesha.
Chacune d'elles devrait
contenir un objet person
avec un nom et des amis.
Nous avons des objets string.
Pour le nom et les amis actuels de Maria,
le nom et les amis actuels de Jamesha.
Disons que nous appelons
maria.addFriend (jamesha).
Nous appelons cette méthode
sur l'objet maria
et nous passons comme argument
l'objet jamesha.
Lorsque cette ligne s'exécute,
la première qu'elle fait
est créer une nouvelle chaîne
à partir de celles-ci.
Ceci sera la nouvelle chaîne créée.
Elle va rassembler friends,
friend.name et un espace.
Friends represente les amis
de l'objet maria
car c'est sur ça que nous
appelons la méthode.
Nous allons à l'objet maria et friends est
actuellement juste TJ avec un espace.
friend.name est l'ami,
l'argument, qui était l'objet Jamesha,
.name, qui est Jamesha.
Et l'espace est juste un espace.
Lorsque ces chaînes seront assemblées,
ça ressemblera à TJ, espace,
Jamesha, espace.
Maintenant, la chaîne créée par cette
partie sera assigné à la variable friends.
Ainsi, l'ancienne référence disparaîtra
et une nouvelle sera créée.
Et maintenant, Jamesha apparaît
dans les amis de Maria.
La vieille chaîne friends qui contenait
que TJ pourrait être encore là
et elle n'a pas changé.
Mais la variable friends
dans l'objet Maria
contient maintenant une référence
à une chaîne différente.
ちょっと難しかったでしょうか これが答えです
他にも方法はありますが
これが一番シンプルだと思います
正解しなくても大丈夫です
さらに練習問題をやっていきましょう
このメソッドを実装するために
細かい仕掛けがあります 例題を見てみましょう
2つの変数があります
1つはmariaでもう1つはjameshaです
それぞれがnameとfriendsを持った
personオブジェクトを含んでいます
またStringオブジェクトにmariaとjameshaの
それぞれの名前と現在の友人があります
maria.addFriend(jamesha)で
呼び出してみましょう
このメソッドをmariaオブジェクトに呼び出して
jameshaオブジェクトへ代入します
この行を実行すると
まずここから新しい文字列が作られます
ここに新しい文字列が入りfriendsと
friends.name及びスペースが一緒に出てきます
friendsはmariaオブジェクトの友人のことで
そのメソッドを呼び出していました
Mariaオブジェクトへ行くと
現在の友人はTJスペースです
friend.nameは引数friendでJamesha
オブジェクトから.nameにJameshaが入ります
スペースはそのままスペースでこの文字列が
一緒になると “TJ Jamesha ”となります
ここで作られた文字列は
friends変数に代入されます
古い情報はなくなり新しい情報に更新されます
そしてJameshaがMariaの友人と表示されます
しかし“TJ ”のみの古い友人の文字列も
まだ残ったままで変化はありませんが
Mariaオブジェクトのfriends変数は
異なった文字列を含んでいます
조금 어려웠을 겁니다. 답은 이렇게 생겼을 겁니다.
다른 방법들도 있겠지만, 저의 답은 이렇습니다. 만약
이해하지 못해도 괜찮습니다. 조금 있다가 더 많은 예제가 있습니다.
이 예제부터 봅시다. 변수 두 개가 있다고
생각합시다.. 하나는 Maria 또 하는 Jamesha입니다. 각각의 변수는
name과 friends 인스턴스 변수들을 포함하는 person 객체를 저장하고 있어야 합니다.
Maria아의 이름, 친구 목록, Jamesha의 이름, 그리고 친구 목록을 위한 문자열 객체가 있습니다.
Maria.addFriend(jamesha)를 호출합시다. Maria 객체에 메소드를 호출하고
jamesha 객체를 매개변수로 전달합니다. 이 코드가 실행되면 첫 번째로 하는
일은 바로 새로운 문자열을 이 변수들로부터 만들 겁니다.
이 변수가 만들어진 새로운 문자열입니다. 이 변수는
friends, friend.name 그리고 빈 칸을 더할 겁니다. friends는
Maria 객체의 friends입니다. 왜냐하면 메소드로부터 호출된 값이기 때문이죠.
그래서 Maria 의 friends가 갖고 있는 값은 "TJ " 입니다. friend.name은 friend, 즉
Jamesha.name를 갖고 있는 매개변수. 값은 "Jamesha" 입니다. 그리고
띄어쓰기는 그냥 띄어쓰기 입니다. 이제 문자열을 다 합하면
"TJ Jamesha "와 같을 겁니다. 여기서 만들어진 문자열은 friends 변수 안에
저장될 겁니다. 그래서 전에 있던 참조는 없어지고 새로운 참조가 만들어
집니다. 그런 후에 Jamesha가 Maria의 친구목록에 등장합니다. 변하기 이전의
friends 변수는 TJ를 저장하고 있습니다. 그리고 변하지 않았습니다. 하지만
Maria 객체에 있는 friends 변수는 다른 문자열을
참조하고 있습니다.
Dat was misschien lastig.
Het antwoord zou er ongeveer
zo uit moeten zien.
Er zijn andere mogelijkheden,
maar voor mij is dit de eenvoudigste.
Als je dit niet door hebt,
geen probleem.
Er komen meer oefeningen aan.
Er zijn subtiele aspecten over
hoe deze methode werkt,
dus laten we een voorbeeld nemen.
Stel je voor dat er twee variabelen zijn,
een voor Maria en een voor Jamesha.
Elk van deze zou een persoonsobject
moeten bevatten
met een naam en vrienden.
We hebben string-objecten.
Voor Maria's naam en
Maria's huidige vrienden,
Jamesha's naam en
Jamesha's huidige vrienden.
Laten we zeggen dat we
maria.addFriend (jamesha) noemen.
We roepen deze methode aan
op het maria-object
en we geven het Jamesha-object
als argument door.
Wanneer deze regel wordt uitgevoerd,
het eerste wat het doet
is een nieuwe reeks aanmaken
van deze reeksen.
Dit is de nieuwe reeks
die gemaakt wordt.
Het zal friends, friend.name
en een spatie samenstellen.
friends is de vrienden van
het maria-object,
want dat is waar we de methode
op aanroepen.
We gaan naar het Maria-object en friends
is momenteel gewoon TJ met een spatie.
friend.name is de vriend,
het argument, het Jamesha-object,
.name, wat Jamesha is.
En " " is slechts een spatie.
Dus, wanneer deze reeksen
worden samengesteld,
lijkt het op TJ, spatie,
Jamesha, spatie.
Nu wordt de reeks die door
dit deel is gemaakt,
toegewezen aan de friends-variabele.
De oude referentie verdwijnt en
wordt er een nieuwe aangemaakt.
En nu verschijnt Jamesha
in de vrienden van Maria.
De string van de oude vrienden die
alleen TJ bevat, kan er nog steeds zijn.
En die is niet veranderd, maar
de friends-variabele in het Maria-object
bevat nu een verwijzing
naar een andere reeks.
Chỗ này hơi rắc rối một chút. Câu trả lời của bạn nên giống như thế này.
Có thể có nhiều cách để thực hiện, nhưng tớ nghĩ đây là cách dễ nhất rồi.
Nếu bạn vẫn chưa hiểu, cũng không sao. Còn nhiều bài luyện tập nữa mà.
Có vài gợi ý bên dưới sẽ giúp bạn hiểu được method này, ta cùng làm thử một ví dụ nhé.
Giả sử ta có 2 biến, một cho Maria và một cho Jamesha. Mỗi biến nên
chứa một object Person, với một cái name và friends. Chúng ta có vài string object ở đây.
Cho Maria's name, Maria's current friends, Jamesha's name và Jamesha's current
friends. Giả sử ta gọi maria.addFriend(jamesha). Ta gọi method này bằng
object maria và ta truyền vào một argument (tham số) là object Jamesha. Bây giờ,
ta cho chạy dòng này. Điều đầu tiên nó làm là tạo ra một string mới từ
chỗ này. Đây sẽ là một string mới được tạo. Nó đặt
friends, friend.name, và khoảng trắng cạnh nhau. Friends là là friends của object maria
bởi vì ta gọi method này bằng nó (chỉ object maria). Vậy, ta đi đến object Maria,
và friends hiện tại chỉ có mỗi "TJ", với một khoảng trắng. friend.name chính là
friend, là cái argument, gồm có object jamesha.name, chính là "Jamesha".
Còn chỗ này chỉ là khoảng trắng. Cho nên, khi những strings này đặt cạnh nhau, nó sẽ giống như
TJ Jamesha. Giờ thì cái string được tạo ra bởi phần này sẽ được gán vào
biến friends. Vậy, chỗ này sẽ được thay bằng
một giá trị mới. Còn bây giờ, Jamesha xuất hiện trong đống friends của Maria. Cái string friends cũ
chỉ chứa mỗi TJ có thể vẫn ở đâu đó. Và nó vẫn chưa thay đổi gì,
nhưng biến friends của object Maria giờ đã chứa một reference (tham chiếu) tới
một string khác.