創建對象

開放
創建對象 - 1

“嗨,又是你最喜歡的老師。既然你取得瞭如此大的進步,我決定告訴你關於物體以及如何使用它們的知識。”

要創建一個對象,您需要輸入關鍵字‘new’,然後輸入它的類型名稱(類名)。例如,假設我們有一個名為‘Cat’的類:”

代碼 描述
Cat cat;
聲明一個名為 cat 的 Cat 引用變量。變量 cat 的值為空。
new Cat();
創建一個貓對象。
Cat cat = new Cat();
創建一個名為 cat 的 Cat 引用變量。
創建一個新的貓對象。將對新創建的對象的引用分配給變量 cat。
Cat kitty = new Cat();
Cat smokey = new Cat();
創建了兩個對象。對它們的引用被分配給兩個不同的變量。
Cat kitty = new Cat();
Cat smokey = new Cat();

smokey = kitty;
創建了兩個對象。對它們的引用被分配給兩個不同的變量。

然後我們將變量 smokey 設置為對變量 kitty 引用的對象的引用。這兩個變量現在都引用第一個創建的對象。
(因為第二個對像不再被任何地方引用,現在被認為是垃圾)

Cat kitty = new Cat();
Cat smokey = null;

smokey = kitty;

kitty = null;
創建一個 Cat 對象,並將對它的引用分配給第一個變量 (kitty)。第二個變量 (smokey) 存儲一個空 (null) 引用。

兩個變量都引用同一個對象。

現在只有 smokey,而不是 kitty,指的是一個對象。

“如果我們創建了一個對象並且沒有在任何變量中保存引用會發生什麼?”

“如果我們只是創建一個對象而沒有將其分配給變量,Java 機器會創建它然後聲明它為垃圾(未使用的對象)。一段時間後,該對象將在垃圾收集期間被處理掉

“如何處理我不再需要的物品?”

“你不需要。一旦沒有變量引用一個對象,它就會被標記為垃圾,並在下次收集垃圾時被 Java 機器銷毀。

只要至少有一個對象的引用,它就被認為是活躍的並且不會被銷毀。如果你想更快地處理一個對象,你可以通過將null分配給引用它的所有變量來清除對它的所有引用。

“原來如此,比起前幾節課,這看起來還是挺簡單的。”

“Diego 整晚都在為你考慮任務。他為你做了這個特別的努力。他很有幽默感,你知道嗎?”

1
任務
Java 語法,  等級 2課堂 3
上鎖
One cat isn't enough
As you know, Rome wasn't populated with cats in a day. But objects can be created quickly. Let's start a small society of kitten fans: create two Cat objects, and assign them names. Remember that every cat is an individual, so the names must be different.

1
任務
Java 語法,  等級 2課堂 3
上鎖
Max, Bella, and Jack
If you open this task, you will find an existing Dog class. We need to create several dogs. We've already thought up their stories: we know how they look, what names they respond to, etc. But in this task, we are interested in the following: create three Dog objects, and then name them "Max", "Bella", and "Jack".
1
任務
Java 語法,  等級 2課堂 3
上鎖
Subjective reality
A bad dancer stumbles over his or her own feet, and a programmer can be confounded by his or her programming language. An urban legend, common among young programmers, says: "If you don't code well, Java will come and eat your memory". Why don't you display this saying on the console? And don't forget to protect your memory! It isn't unlimited.
1
任務
Java 語法,  等級 2課堂 3
上鎖
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. Turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

作為 Codegym 大學課程一部分的導師授課片段。報名參加完整課程。


留言
  • 受歡迎
你必須登入才能留言
此頁面尚無留言