Access Modifiers specific the accessiblity or scope of a field, method, constructor, or class.
There are four types of Java access modifiers, and below is a simple table to help us understand quickly.
|Access Modifier||Within class||Within package||Outside package by subclass only||Outside package|
The private access modifier is accessible only within the class.
Worth to talk about
If you make any class constructor private, yo cannot create the instance of that class from outside the class.
A class cannot be private or protected except nested class.
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package.
The protected access modifier is accessible within package and outside the package but through inheritance only.
Worth to talk about.
- It can't be applied on the data member.
- outside the package but through inheritance only means Class B in package BB extends class A in package AA with a protected method
add. Inside package BB the The instance
xof class B can call
x.add(). But the instance
yof Class A still can't call
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Access Modifiers with Method Overriding
Overridden method must not be more restrictive.
Java Exception includes RuntimeException and Non_RuntimeException. It is not necessary to indicate "throw RuntimeException" in method signature.