ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
字段默认为 private ,意味着只有类和它的子类可以访问它们。它们可以被声明为公共字段,通过使用 public 访问修饰符,使它们可以在各处访问。 > Fields are by default private, meaning that only the class and its sub-classes may access them. They can be made public by using the public access modifier, allowing access from anywhere. ~~~ class MyClass { static public function available() { unavailable(); } static private function unavailable() { } } class Main { static public function main() { MyClass.available(); // Cannot access private field unavailable MyClass.unavailable(); } } ~~~ MyClass类的可用字段的访问允许从Main中访问,因为它表示为 public。然而,当访问不可用的字段访问可以从类MyClass内部,但是不能从Main中访问,因为它是private(明确的私有声明,尽管这个标识符在这里是多余的) > Access to field available of class MyClass is allowed from within Main because it is denoted as being public. However, while access to field unavailable is allowed from within class MyClass, it is not allowed from within class Main because it is private (explicitly, although this identifier is redundant here). 例子展示了static字段的可见性,但是成员字段的规则是等价的。下面的示例展示了当继承(第2.3.2节)被使用时的可见性行为。 > The example demonstrates visibility through static fields, but the rules for member fields are equivalent. The following example demonstrates visibility behavior for when inheritance (2.3.2) is involved. ~~~ class Base { public function new() { } private function baseField() { } } class Child1 extends Base { private function child1Field() { } } class Child2 extends Base { public function child2Field() { var child1 = new Child1(); child1.baseField(); // Cannot access private field child1Field child1.child1Field(); } } class Main { static public function main() { } } ~~~ 我们可以看到访问 child1.baseField() 是允许在Child2类中访问,即使child1是不同的类型,Child1 。这是因为字段被定义在它们的通用祖先类Base,相反的,字段 Child1Field不能被从Child2中访问。 > We can see that access to child1.baseField() is allowed from within Child2 even though child1 is of a different type,Child1. This is because the field is defined on their common ancestor class Base, contrary to field child1Field which can not be accessed from within Child2. 省略可见性的修饰符通常默认可见性为 private,但是有例外它会变成 public: > Omitting the visibility modifier usually defaults the visibility to private, but there are exceptions where it becomes public instead: 1. 如果类被声明为 extern 2. 如果字段被声明在一个接口(第2.3.3节) 3. 如果字段重载(第4.3.1节)了一个 public 字段 > 1. If the class is declared as extern. > 2. If the field is declared on an interface (2.3.3). > 3. If the field overrides (4.3.1) a public field. **Protected** >[warning] **花絮**:Protected Haxe没有类似Java和C++等其它面向对象语言中的protected概念。然而,它的private行为等同于那些语言的protected行为,所以Haxe实际上缺少的是那些语言中的 private 行为。 >[warning] **Trivia**: Protected Haxe has no notion of a protected keyword known from Java, C++ and other object-oriented languages. However, its private behavior is equal to those language’s protected behavior, so Haxe actually lacks their real private behavior.