Oop 5 - Access Modifiers
Oop 5 - Access Modifiers
Programming
Lecture 5 – Access
Modifiers
By
Upeksha Kudagamage
Lecturer-SUSL
Access Modifiers
⚫ The access modifiers in java specifies accessibility (scope)
of a data member, method, constructor or class.
⚫ There are 4 types of java access modifiers:
⚫ private
⚫ default
⚫ protected
⚫ public
2
Access Modifier Visibility
3
⚫ Public:
Class, Variables, methods, Constructors
• Protected/ Private:
Variables, methods, constructors
Default:
Class, Variables, methods, Constructors
4
Packages
⚫ A Package can be defined as a grouping of related
types(classes, interfaces, enumerations.
5
Package and Import
⚫ Classes can be organized into packages.
6
Public
⚫ The public access modifier is accessible
everywhere. It has the widest scope among all
other modifiers.
7
Protected
⚫ The protected access modifier is accessible within
package and outside the package but through
inheritance only.
8
Ex:
⚫ we have created the two
packages pack and
mypack.
⚫ The A class of pack
package is public, so can
be accessed from outside
the package. But msg
method of this package is
declared as protected, so
it can be accessed from
outside the class only
through inheritance
9
Private
⚫ The private access modifier is accessible only within
class.
10
Default Access Modifier
⚫ If you don't use any modifier, it is treated as default by
default. The default modifier is accessible only within
package.
11
Ex:
12
public vs. private
⚫ Classes are usually declared to be public
⚫ Instance variables are usually declared to be private
⚫ Methods that will be called by the client of the class
are usually declared to be public
⚫ Methods that will be called only by other methods of
the class are usually declared to be private
13
Access Levels
14
END
15