JavaLearning Note –class(1)
Reference: Java Tutorial (Oracle)
1.modifiers
1). comprehension
Package one: Apple 公司
Package two: Foxconn公司
Alpha: Apple 的对外关系部
Beta: Apple的研发部
AlphaSub: Foxconn 的生产部
那么,标识符可以这么理解(以 Alpha 部门为例)
public | Apple产品 (iPhone, mac,…) 人人可见 |
protected | Apple未公布消息(iPhone 7的配置), Apple员工都知道 Foxconn 的 AlphaSub 接到订单后(继承)也知道 |
default | Apple的iPhone 8研发计划, Apple员工都知道 |
private | Alpha研发部的内部工作, Alpha部门的人直接操作 (getter, setter: 来自其他部门的请求) |
2) Tips on Choosing an Access Level.
1.Use private unless you have a good reason not to.
2.Avoid public except for constants.
Conclusion:prevent unexpected invoke.
2. class methods
class methods (static method) | cannot access instance variables or instance methods, unless use an object reference.???????????? |
cannot use this. keyword, because there is no instance. |
3.Initializing
{ // whatever code is needed for initialization goes here //for instance variable, the block will be copied to every constructor. // with static keyword, it’s used for initialize class variable } |
class Whatever { public static varType myVar = initializeClassVariable(); private static varType initializeClassVariable() { // initialization code goes here // can be reused later if you need to reinitialize the class variable.??????????? } } |