Access Modifiers
Basic
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 |
---|---|---|---|---|
Private | Y | N | N | N |
Default | Y | Y | N | N |
Protected | Y | Y | Y | N |
Public | Y | Y | Y | Y |
Private
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.
Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package.
Protected
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 instancex
of class B can callx.add()
. But the instancey
of Class A still can't cally.add()
Public
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.
权限在继承的过程中只能越来越开放
Exception
Java Exception includes RuntimeException and Non_RuntimeException. It is not necessary to indicate "throw RuntimeException" in method signature.
像Java中的Map的get方法,在函数签名中并不会声明会抛出找不到key的异常。这种异常的声明更应该写到文档中。