简体   繁体   English

'protected'和'protected-static'变量有什么区别?

[英]What is the difference with 'protected' and 'protected-static' variables?

I read a book for OOP and an example about 'protected' access modifier is strange for me. 我读了一本关于OOP的书,关于'protected'访问修饰符的例子对我来说很奇怪。

Summary of example 示例摘要

  1. This example is to test how 'protected' reserved word effects to variables. 此示例用于测试“受保护”保留字对变量的影响。
  2. ClassA has 2 protected variables (static / non-static) ClassA有2个受保护的变量(静态/非静态)

     package a; public Class A { protected int a; protected static int b; } 


  1. ClassB is derived from ClassA and located another package ClassB派生自ClassA并位于另一个包中
  2. ClassB.test has a method to check accessibility (Cannot run) ClassB.test有一个检查可访问性的方法(无法运行)

     package b; public Class B extends ClassA { ClassA x = new ClassA(); // [O] : Executable // [X] : Not-executable void test() { a = 1; // [O] : Derived from ClassA b = 1; // [O] : Derived from ClassA // [X] : a is protected, so only accessible within codes in derived class xa = 1; // A) // [O] : I don't know why it is executable xb = 1; // B) } } 


Actually, b is 'protected' so I thought it cannot be accessed by instance variable like xa = 1; 实际上,b是'受保护的'所以我认为它不能被像xa = 1这样的实例变量访问;
But it can be accessible with 'static' keyword. 但是可以使用'static'关键字访问它。 How can I understand for this? 我怎么能理解这个?

Shortly A) is fine, but why is B) executable ? 不久A)很好,但为什么B)可执行?

The static keyword means that variable belongs to the class itself instead of the objects of said class. static关键字表示变量属于类本身而不是所述类的对象。 You could replace your call to xb with ClassA.b . 您可以使用ClassA.b替换对xb的调用。 Since ClassB extends ClassA , all protected static variables are accessible for all methods of ClassB at all time. 由于ClassB扩展了ClassA ,因此所有protected static变量都可以随时用于ClassB所有方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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