Visibility in Java
Describes variable and method visibility in the Java programming language. Includes an interactive example of Java inheritance in two different packages.
Prerequisites
- Understand Java primitive types and variables
- Understand Java methods
- Understand Java class and objects
Objectives
- Know when to use
private
, (default),protected
, andpublic
attributes and methods - Declare attributes and methods as
private
, (default),protected
, andpublic
Purpose of Visibility
- Visibility modifiers do not change the scope (ownership or lifetime) of a variable or method.
- They simply limit where a variable or method is visible (usable, changeable, or callable).
Visibility in Java
Java has four visibility modifiers (least visible to most visible):
private
, (default), protected
,
public
(least visible) | (most visible) | |||
private | (default) | protected | public | |
---|---|---|---|---|
Can be accessed from the same class | ✓ | ✓ | ✓ | ✓ |
Can be accessed from the same package | ✓ | ✓ | ✓ | |
Can be accessed from any child class | ✓ | ✓ | ||
Can be accessed from anywhere | ✓ |
Demonstration
- Move your mouse pointer over a variable declaration and your browser will highlight in yellow the classes where that variable is visible.
- Move your mouse pointer over a method header and your browser will highlight in orange the variables that method can use.
| |||||||||
|