Below are the closest equivalents to C # access modifiers in Java and Scala. In the case of the internal (available inside the same assembly) exact equivalent is not. In Java, you can restrict access to the same package, but packages are more directly equivalent to C # namespaces than their nodes.
("no modifier" in the following table is interpreted as applying to class members. That is, in C # class members without a modifier are private. This does not apply to top-level types that are internal by default.)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | C# | Java | Scala | Meaning | |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | no modifier | private (1) | private | accessible only within the class where it is defined | | private | | | | |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | protected | -- | protected | accessible within the class and within derived classes (2) | |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | internal | no modifier | private[package_name] | accessible within the same assembly (C
(1) In Java, private members of the inner class are visible to the outer class, but this is not true in C # or Scala. In Scala, you can say private [X], where X is the outer class to get Java behavior.
(2) In C # and Scala, a protected member is visible inside a class if it is a member of an instance of that class or another derived class, but is not a member of an instance of a less organized class, a derived class. (The same is true in Java, except where it is available due to being in the same package.)
Example (in C #):
class Base { protected void Foo() {} void Test() { Foo(); // legal this.Foo(); // legal new Base().Foo(); // legal new Derived().Foo(); // legal new MoreDerived().Foo(); // legal } } class Derived : Base { void Test1() { Foo(); // legal this.Foo(); // legal new Base().Foo(); // illegal ! new Derived().Foo(); // legal new MoreDerived().Foo(); // legal } } class MoreDerived : Derived { void Test2() { Foo(); // legal this.Foo(); // legal new Base().Foo(); // illegal ! new Derived().Foo(); // illegal ! new MoreDerived().Foo(); // legal } }
(3) In Scala, you can get Java behavior by specifying the innermost package, but you can also specify any inclusive package.
source share