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 into the examples with methods:
Practiceare in the same package.
- We can use
public, protected, and defaultmethods in
Practiceclass, but we have compiler error for our
privatemethod. Because it is accessible within the same class only.
The access modifiers are needed to encapsulate our code and used with one of the OOP concepts — encapsulation.
This article is part of the series of articles to learn Java programming language from Tech Lead Academy:1. Introduction to programming
2. OS, File, and File System
3. Working with terminal
4. Welcome to Java Programming Language
5. Variables and Primitives in Java
6. Methods with Java
7. Java Math Operators and special operators
8. Conditional branching in Java
9. Switch statement in Java
10. Ternary operator in Java
11. Enum in Java
12. String class and its methods in Java
13. Loops in Java
14. Access modifiers in Java
15. Static keyword in Java
16. The final keyword in Java
17. Class and Object in Java
18. Object Oriented Programming in Java
19. OOP: Encapsulation in Java
20. Inheritance in Java
21. Abstraction in Java
22. Polymorphism in Java
23. Overriding vs Overloading in Java
24. OOP Design Principles in Java
25. Array in Java
26. Data Structures with Java
27. Collection framework in Java
28. ArrayList in Java
29. Set in Java
30. Map in Java
31. LocalDate in Java
32. Exception in Java
33. IO in Java
34. Design Patterns
35. Generics in Java
36. Multithreading in java
38. Big O Notation for coding interviews
39. Top 17 Java coding interview questions for SDET