CodeGym /Kursus Jawa /2. modul: Java Core /Urutan inisialisasi variabel

Urutan inisialisasi variabel

2. modul: Java Core
tingkat , wulangan
kasedhiya

"Halo, Amigo! Dina iki, Bilaabo bakal ngomong babagan urutan variabel sing diinisialisasi ."

Mbayangno sampeyan lagi ndeleng sawetara kode. Nilai apa sing ditampa dening variabel?

Kode
class Cat
{
 public int a = 5;
 public int b = a + 1;
 public int c = a * b;
}
Kode
class Cat
{
 public int a = getSum();
 public int b = getSum() - a;
 public int c = getSum() - a - b;

 public int getSum()
 {
  return a + b + c;
 }
}

"Apa pancen diijini?"

"Mesthi wae. Urutan cara lan kolom anggota kelas diumumake ora penting. "

Kelas dimuat saka ndhuwur nganti ngisor, dadi penting yen lapangan mung ngakses kolom liyane sing wis dimuat. Ing conto, b bisa ngakses a , nanging ora ngerti apa-apa bab c .

"Lan apa sing bakal kelakon?"

"Nalika variabel digawe, padha entuk nilai standar."

Kode Apa pancene kedadeyan
class Cat
{
 public int a = 5;
 public int b = a + 1;
 public int c = a * b;
}
class Cat
{
 public int a = 0;
 public int b = 0;
 public int c = 0;

 public Cat()
 {
  super();

  a = 5;
  b = a + 1; //5+1 = 6
  c = a * b; //5*6 = 30
 }
}
class Cat
{
 public int a = getSum();
 public int b = getSum() - a;
 public int c = getSum() - a - b;

 public getSum()
 {
  return a + b + c;
 }
}
class Cat
{
 public int a = 0;
 public int b = 0;
 public int c = 0;

 public Cat()
 {
  super();

  a = getSum(); //(a+b+c)=0
  b = getSum() - a; //(a+b+c)-a=b=0
  c = getSum() - a - b; //(a+b+c)-a-b=c=0
 }

 public getSum()
 {
  return a + b + c;
 }
}

"Suci moly! Gampang banget. Matur nuwun, Bilaabo. Sampeyan pancen kanca sejati!"

"Hore! Bilaabo duwe kanca!"

Komentar
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION