为什么一些常量公众和其他在Android库code私人他在、常量、公众、私人

2023-09-06 10:07:41 作者:浪子

问题

为什么一些常量是公共修改下,而其他一些私人?是那些在公共可以从使用​​库的应用程序叫什么?如果是这样,如何​​从一个应用程序调用的常数,它是这样的: CertainLibraryClass.ActivityResult code code_A

  

code

 公共类CertainLibraryClass {    公共类ActivityResult code {    公共静态最终诠释code_A = 0X02;    公共静态最终诠释code_B = 0X03;    公共静态最终诠释code_C = 0X04;    }    公共类版本code {        私有静态最终诠释VERSION_MAJOR = 1;        私有静态最终诠释VERSION_MINOR1 = 0;        私有静态最终诠释VERSION_MINOR2 = 2;    }// ....} 

解决方案

为什么一些常量是公共修改下?

答:让所有其他类都可以访问它如 RESULT_OK 成功

为什么一些常量是私人修改下?

答:那么,只有这个类可以访问它。

例如。考虑你调用的getId()从你的类libarary功能

 公共类CertainLibraryClass {私有静态诠释ID = 0;公共静态INT的getId(){返回ID + 1;} 

在这里,你不是直接访问 ID 字段,而不是你调用的getId()函数,最终返回ID,这意味着 ID 变量是内部使用 CertainLibraryClass

Problem

干货 9个容易忽略的iOS与Android间的交互差异

Why some constants are under the public modifier while some other private? Are those under public can be called from applications that use the library? If so, how to call the constant from an app, is it like this: CertainLibraryClass.ActivityResultCode.CODE_A?

Code

public class CertainLibraryClass {
    public class ActivityResultCode {
    public static final int CODE_A = 0X02;
    public static final int CODE_B = 0X03;
    public static final int CODE_C = 0X04;
    }
    public class VersionCode {
        private static final int VERSION_MAJOR = 1;
        private static final int VERSION_MINOR1 = 0;
        private static final int VERSION_MINOR2 = 2;
    }
// ....
}

解决方案

Why some constants are under the public modifier?

Ans: So that all other classes can access it e.g.RESULT_OK,SUCCESS.

Why some constants are under the private modifier?

Ans:So that only that class can access it

e.g. consider you are calling getId() libarary function from your class

public class CertainLibraryClass {
private static int ID=0;

public static int getId()
{
return ID+1;
}

here you are not accessing ID field directly ,instead you are calling getId() function which ultimately returns the id, it means that ID variable is internally used by CertainLibraryClass class