01/10/2018, 17:33

Tạo Object từ 1 Class trong Java

Chào các anh chị, em đang đọc sách đến đoạn này chưa hiểu lắm. Mong anh chị giúp!

Declaring Objects

As just explained, when you create a class, you are creating a new data type. You can use this type to declare objects of that type. However, obtaining objects of a class is a two-step process. First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator dynamically allocates (that is, allocates at runtime) memory for an object and returns a reference to it. This reference is, essentially, the address in memory of the object allocated by new. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. Let’s look at the details of this procedure.

Giả sử en có một Class Box

class Box {}

Thì 2 cách khai báo dưới đây khác gì nhau ạ:

Box box1 = new Box();
Box box1;
Nguyễn Đình Anh viết 19:39 ngày 01/10/2018

Box box1 = new Box();

Đã gán giá trị cho box1new Box();

Box box1;

Bạn mới chỉ khai báo là có 1 Box box1; chứ chưa gán giá trị, box1 lúc này = null

Bài liên quan
0