Access modifiers in Java

Access modifiers are used to control access for variables, methods, and sometimes inner classes.

There are 4 access modifiers available:

public — accessible from everywhere. If we mark it as public it will be accessible from everywhere.

protected — accessible within the same package and child classes.

default — if we don't put anything it’s the default access modifier. It’s accessible within the same package only.

private — accessible within the same class only.

Let’s take a look at the examples with methods:

  • Main and Practice are in the same package.
  • We can use public, protected, and default methods in Practice class, but we have compiler error for our private method. Because it is accessible within the same class only.

The access modifiers are needed to encapsulate our code and are used with one of the OOP concepts — encapsulation.

--

--

--

Software Developer, Java Instructor https://www.techleadacademy.io/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Machine Learning With GPU (1): CUDA

High Definition Render Pipeline — Fog

Streaming Protocols: RTMP

Leading IT Teams in the Gaming Industry While Empowering Herself and Everyone Around Her

Admin Site Customization — Django

I suck at math, but I can code — you can too

Managing Primadonnas in the Real World

What we learned from taking an online AWS cert exam

aws certification

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Beknazar

Beknazar

Software Developer, Java Instructor https://www.techleadacademy.io/

More from Medium

Why Learn Java in 2021

Java Programs

Pyramid Pattern of Numbers code in java

Comparison Between Inheritance and Polymorphism in Java