Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีประกาศ Reference Types ใน JShell Java 9

JShell เป็นเครื่องมือโต้ตอบใน Java 9 รับ user input ประเมินผลและพิมพ์ output

ต่างจาก value type, reference type ไม่เก็บค่าโดยตรง แต่เก็บ address ที่เก็บค่า หมายถึง reference type มี pointer to another memory location ที่ hold data Reference types ได้แก่ String, arrays, class, และ delegates

Snippet 1: สร้าง Object Instance

jshell> class Animal { ...> } 
| created class Animal

jshell> Animal dog = new Animal();
dog ==> Animal@73846619

เมื่อสร้าง new Animal() object จะถูกสร้างบน heap memory Animal@73846619 แสดงว่า object อยู่บน Heap ที่ address 73846619

Snippet 2: Multiple Objects

jshell> class Animal { 
   ...> int id; 
   ...> public Animal(int id) { 
   ...>     this.id = id; 
   ...> } 
   ...> } 
| created class Animal

jshell> Animal dog = new Animal(10);
dog ==> Animal@6adede5

jshell> Animal cat = new Animal(20);
cat ==> Animal@5025a98f

สร้าง Animal objects 2 ตัว บน Heap memory locations (references) ถูกเก็บใน reference variables dog และ cat ใน Java ทุก classes เป็น Reference Types ยกเว้น primitive variables ทุก instances/objects เก็บบน Heap references ถูกเก็บใน reference variables

Snippet 3: Primitive vs Reference Comparison

jshell> int i = 5;
i ==> 5

jshell> int j;
j ==> 0

jshell> j = i;
j ==> 5

jshell> j = 10;
j ==> 10

jshell> i;
i ==> 5  // i ไม่เปลี่ยน

jshell> i == j;
$11 ==> false

jshell> j = 5;
j ==> 5

jshell> i == j;
$13 ==> true

j = i คัดลอกค่าของ i ไป j ตอนเปลี่ยน j ค่า i ไม่ได้รับผลกระทบ primitive variables เปรียบเทียบค่าโดยตรง

Reference Type Behavior

jshell> Animal dog = new Animal(10);
jshell> Animal anotherDog = dog;  // copy reference
jshell> anotherDog.id = 20;
jshell> dog.id
$ ==> 20  // เปลี่ยนด้วย! เพราะชี้ object เดียวกัน

ตารางเปรียบเทียบ Primitive vs Reference

คุณสมบัติ Primitive Types Reference Types
ตัวอย่าง int, double, boolean, char String, Arrays, Classes, Interfaces
เก็บค่า โดยตรง (stack) reference/address (heap)
Assignment Copy value Copy reference
Comparison (==) เปรียบเทียบค่า เปรียบเทียบ reference (address)
Default value 0, 0.0, false, '\u0000' null
Null possible ไม่ได้ ได้

ข้อสังเกตสำคัญ

  • ใน JShell ทุก declaration เป็น top-level จึงไม่ต้องอยู่ใน class
  • Variables เก็บค่า reference ไม่ใช่ object โดยตรง
  • ใช้ == เปรียบเทียบ reference, ใช้ .equals() เปรียบเทียบเนื้อหา
  • Arrays เป็น reference types - assignment คัดลอก reference