Access Modifiers for Methods and Attributes
The following modifiers are used for attributes, methods, and constructors.
The private
and protected
modifiers will be discussed when the inheritance is covered.
Modifier |
Description |
public
|
The code is accessible by any other class.
|
private
|
The code is only accessible within the declared class.
|
default or nothing
|
The code is only accessible by classes in the same package.
This is used when you do not specify a modifier.
|
protected
|
The code is accessible in the same package and subclasses.
|
The static
and public
Methods
A method could have either
static
or
public
keyword or both.
A
static
method means that it can be accessed without creating an object of the class, unlike
public
, which can only be accessed by objects.
The example below demonstrates the differences between
static
and
public
methods: