— Scott McNealy, Sun Microsystems Chairman, President and ceo



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

numbers 
and
statics
you are here
4
277
Static methods can’t use non-static 
(instance) variables!
Static methods run without knowing about any particular 
instance of the static method’s class. And as you saw on 
the previous pages, there might not even be any instances 
of that class. Since a static method is called using the class 
(Math.random()) as opposed to an instance reference (t2.play()), 
a static method can’t refer to any instance variables of the 
class. The static method doesn’t know which instance’s variable 
value to use.
If you try to use an 
instance variable from 
inside a static method, 
the compiler thinks, 
“I don’t know which 
object’s instance variable 
you’re talking about!” 
If you have ten Duck 
objects on the heap, a 
static method doesn’t 
know about any of them.
public class Duck {
private int size;
public static void main (String[] args) {
System.out.println(“Size of duck is “ + size);
}
public void setSize(int s) {
size = s;
}
public int getSize() {
return size;
}
}

If you try to compile this code:


I’m sure they’re 
talking about 
MY 
size variable.
No, I’m pretty sure 
they’re talking about 
MY size variable.
Which Duck? 
Whose size?
You’ll get this error:
File Edit Window Help Quack
% javac Duck.java
Duck.java:6: non-static variable 
size cannot be referenced from a 
static context
System.out.println(“Size 

Download 40,57 Mb.

Do'stlaringiz bilan baham:
1   ...   260   261   262   263   264   265   266   267   ...   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