简体   繁体   中英

static variables can not be accessed by other class

public static DevicePolicyManager minochaDevicePolicyManager;
public static ComponentName minochaDevicePolicyAdmin;

the above code is in my MainActivity java class above the onCreate . Since it is static shouldn't it be accessed by other classes? i have this class MyBroadCastReceiver (code below)

public class MyBroadcastReceiver  extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    String LOG_TAG="DevicePolicyAdmin";
    Log.v(LOG_TAG, "Service Started");
    Calendar c = Calendar.getInstance();
    int hour=c.get(Calendar.HOUR_OF_DAY);
    int  minute=c.get(Calendar.MINUTE);
    Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
    String date = sdf.format(calendar.getTime());
    String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);
    minochaDevicePolicyManager.resetPassword(str,0);
}
}

The minochaDevicePolicyManager can not be resolved in the BroadcastReceiver class. Why? it is a static variable so it should be able to be accessed by other classes right?

To access a static field from a second class you need to import static the field, or access by the class name.

 minochaDevicePolicyManager.resetPassword(str,0);

should be something like

 MainActivity.minochaDevicePolicyManager.resetPassword(str,0);

static variables are attached to the class not it's object, which means it can be called directly from the Class name without creating an object.

You are trying to access the variable like a local variable.

Change

minochaDevicePolicyManager.resetPassword(str,0);

to

MainActivity.minochaDevicePolicyManager.resetPassword(str,0);

您应该像这样访问它:

MainActivity.minochaDevicePolicyManager

静态变量是类变量。如果您从同一个类调用静态变量,那么您只能使用类名调用,但是当您从其他类调用静态方法时,您应该使用类名称点方法名称,即

CLASS.method()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM