Saturday, November 10, 2012

Access Modifiers in Java

Read some notes online, but just to summarize here for later convenient look-up.

There are four levels of accessibility in Java: public, protected, package, and private. From the blog in JavaPapers.com, I am also summarizing in a table below to show the differences.

Access LevelSame ClassSame PackageSubclassesOther Packages
publicYYYY
protectedYYYN
packageYYNN
privateYNNN

Besides, below lists some notes about the access modifier usage and default level.
  1. Classes can be qualified by public or no modifier only. When qualified without any modifier, by default the access level is package.
  2. Interfaces can be qualified by public or no modifier only. When qualified without any modifier, by default the access level is also package.
  3. Class methods and fields can be qualified by all, public, protected, private, or no modifier. When qualified without any modifier, by default the access level is package.
  4. Interface methods and fields can be qualified by public or no modifier only. When qualified without any modifier, by default the access level is public.
  5. Inheritance in Java can be public only and this is the default. Unlike C++, there is no protected or private inheritance.
  6. The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

References
JavaPapers.com
TutorialsPoint
Default access modifier of interface
Inheritance in Java?
Java Tutorial

No comments:

Post a Comment