— Scott McNealy, Sun Microsystems Chairman, President and ceo



Download 40,57 Mb.
Pdf ko'rish
bet267/555
Sana26.05.2022
Hajmi40,57 Mb.
#609235
1   ...   263   264   265   266   267   268   269   270   ...   555
Bog'liq
Head First Java (Kathy Sierra, Bert Bates) (z-lib.org)

class Duck {
int duckCount = 0;
public Duck() {
duckCount++;
}
}
No, that wouldn’t work because duckCount is an 
instance variable, and starts at 0 for each Duck. You 
could try calling a method in some other class, but 
that’s kludgey. You need a class that’s got only a single 
copy of the variable, and all instances share that one 
copy. 
That’s what a static variable gives you: a value shared 
by all instances of a class. In other words, one value 
per class, instead of one value per instance.
this would always set 
duckCount to 1 each time 
a Duck was made
public class Duck {
private int size;
private static int duckCount = 0;

public Duck() {
duckCount++;
}
public void setSize(int s) {
size = s;
}
public int getSize() {
return size;
}
}
Now it will keep 
incrementing each time 
the Duck constructor runs, 
because duckCount is static 
and won’t be reset to 0.
The static duckCount 
variable is initialized ONLY 
when the class is first 
loaded, NOT each time a 
new instance is made.
A Duck object doesn’t keep its own copy 
of duckCount. 
Because duckCount is static, Duck objects 
all share a single copy of it. You can think 
of a static 
variable as a 
variable that 
lives 
in a CLASS instead of in an object.
Du
c
k obje
c

size: 12
duckCount: 4
Du
c
k obje
c

size: 22
duckCount: 4
Du
c
k obje
c

size: 8
duckCount: 4
Du
c
k obje
c


Download 40,57 Mb.

Do'stlaringiz bilan baham:
1   ...   263   264   265   266   267   268   269   270   ...   555




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish