Access Modifiers for Classes
The public
keyword appears in almost all of our examples:
public class MyClass { ... }
It is an access modifier, which is used to set the access level for classes, attributes, methods, and constructors.
They are divided into two groups:
- Access modifiers, which control the access level, and
- Non-access modifiers, which do not control access level, but provide other functionality.
It will be discussed when the inheritance is covered.
Access Modifiers for Classes
For classes, you can use either public
or default:
Modifier |
Description |
public
|
The class is accessible by any other class.
|
default or nothing
|
The class is only accessible by classes in the same package.
This is used when you do not specify a modifier.
|
The public
Keyword for Classes
A
public
keyword is an access modifier.
It can be assigned to variables, methods, constructors, and classes.
It is the most non-restricted type of access modifier.
- The public access modifier is accessible everywhere.
So, we can easily access the public inside and outside the class and package.
- If a program contains multiple classes, at most one class can be assigned as public.
- If a class contain a public class, the name of the program must be similar to the public class name.
- If you are overriding any method, overriding method (i.e., declared in the subclass) must not be more restrictive.
So, if you assign public to any method or variable, that method or variable can be overridden by subclass using public access modifier only.
Beauty is only skin deep.
|