Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion regarding access specifiers in Java and C#

I was comparing access modifiers in Java and C#. I wanted to find an alternative of C#'s protected internal in Java. But I noticed that protected modifier is different in both the languages (C# and Java). protected in Java is equivalent to protected internal of C# because the member gets accessible within the same package too.

I have two questions

  • Why have they created different meanings to same modifier in Java and C#?
  • How can I have protected of C# (Access is limited to the containing class or types derived from the containing class.) in Java?
like image 456
Shashwat Avatar asked Nov 04 '22 16:11

Shashwat


1 Answers

Why have they created different meanings to same modifier in Java and C#?

A choice had to be made between simplicity and the ability to precisely specify different access rights. Different choices were made by the creators of Java and (later) by the creators of C#.

How can I have protected of C# (Access is limited to the containing class or types derived from the containing class.) in Java?

You can't. Java is more limited on this point.

But you should probably limit your use of the protected keyword as in both use it means a breaking of the general encapsulation principle. This use is sometimes useful, as a too strict language can mean too much useless code, but beware not to make something that will be too tied and hard to change and maintain. Giving access to internal fields or methods to overriding classes often means you have an heavy hierarchy with too much implementation coupling (prefer composition over hierarchy for maintainability).

Note that a variable or method declared without any access control modifier is available to any other class in the same package. In my opinion, that's saner than allowing access by subclasses of any package.

Here's the complete grid :

enter image description here

like image 104
Denys Séguret Avatar answered Nov 15 '22 00:11

Denys Séguret