Declaring Methods  «Prev  Next»


Lesson 7Access modifiers
ObjectiveExplain how Access Specifiers are used to control access to Variables and Methods

Java Access modifiers

Access modifiers are used to control access to a class, interface, constructor, variable, method, or inner class. Java supports the public, protected, and private access modifiers. It also supports a default access, referred to as package access or friendly access, when no other modifier is specified. Default or Package access: The default access that occurs when no access modifier is specified. Access is restricted to the package in which an item is declared. Also referred to as friendly access. Pay attention to access modifiers. You are likely to see a few certification exam questions that will test your knowledge of them.

public Access Modifier

A public class or interface is accessible outside of its package. A public variable, method, constructor, or inner class is accessible anywhere that the class may be accessed.

Public classes and interfaces
Public classes and interfaces


Top-level classes and interfaces may be declared as
  1. public or
  2. default (no modifier)
access . Top-level classes may not be declared protected or private.

Protected

A protected variable, method, constructor, or inner class may be accessed in the package, class and subclasses of the class in which it is declared.

protected variable, method, constructor, or inner class
Protected variable, method, constructor, or inner class

Java Language Reference

Private

A private variable, method, constructor, or inner class may only be accessed in the class in which it is declared.

private variable, method, constructor, or inner class
private variable, method, constructor, or inner class

Package or default access

Package access is the default access when no other access modifier is specified. An item that is declared with package access may only be accessed within the package it is declared.