我是java初学者,我试图从我买来学习java的书中理解静态的概念。但是,由于我在程序中的实验,我很困惑。书上说 static 不能引用这个关键字,这很好,直到我开始使用普通函数而不是 static 。在这里,我能够使用 this 关键字访问静态变量! (参见下面代码中的displayMobileSpecs函数)
import java.util.Random;
class Static {
public static void main(String[] com){
System.out.println("By default the mobile is having "
+ Mobile.RAM + "gigabytes of RAM and"
+ Mobile.CameraMP + " mega pixels of camera");
Mobile S4mini = new Mobile("S4 Mini" , 4 , 16);
S4mini.displayMobileSpecs(true);
Mobile mob2 = new Mobile("fdf" , 23 , 45);
mob2.displayMobileSpecs(true);
S4mini.displayMobileSpecs(false);
}
}
class Mobile{
static int RAM;
static int CameraMP;
Random rand = new Random();
double InternalMemorySpace;
double ExternalMemorySpace;
String modelNo;
Mobile(String modelName,double internalMem , double externalMem)
{
this.modelNo = modelName;
this.InternalMemorySpace = internalMem;
this.ExternalMemorySpace = externalMem;
}
static {
RAM = 4;
CameraMP = 12;
System.out.println("The Static part of the class is executed");
}
void displayMobileSpecs(boolean change){
if(change)
this.RAM = (int) rand.nextInt(8) + 2;
System.out.println(this.RAM + " , " + Mobile.RAM);
}
}
那么静态变量可以使用 this 访问,但不能在静态函数中访问还是什么?我真的很困惑,在我看来这是一个非常愚蠢的问题,但请回答我。
(注意:顺便说一句,请不要介意程序中使用移动设备的荒谬示例。谢谢:) )
最佳答案
static variables could be accessed using this but not in the static functions
在静态 block 或静态方法中,没有实例可引用,因此不允许使用“this”关键字。
Why am i able to use this keyword with static variables in java
但是你可以在非静态方法中引用“this”,也可以在非静态方法中使用带有“this”关键字的引用静态变量。这里“this”指向当前对象。
关于java - 为什么我可以在java中使用this关键字和静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262060/