Access modifiers are keywords in Java that control the visibility and accessibility of classes , methods and constructors and data members.
There are four types of access modifiers in Java
Public - This makes the class, methods , data members accessible from anywhere in the program.
public class MyClass {
public void display() {
System.out.println("Public method");
}
}
Private -Private keyword makes sure that the data members are only accessible within the same class where they are declared. They are not accessible to other classes even within the same package.
public class MyClass {
private int data = 10;
private void display() {
System.out.println("Private method");
}
}
Protected - Protected keyword makes sure that the data members and the methods are accessible within the same package and subclasses.
public class MyClass {
protected int data = 10;
protected void display() {
System.out.println("Protected method");
}
}
Default - When none of the keyword is used to define the access of the class, method or data members the default access modifier is applied to it which makes it accessible only within the same package.
class MyClass { // default access
void display() { // default access
System.out.println("Default method");
}
}
Thanks for reading , try simplifying more in the comments and help others :>
Top comments (2)
There is no
default
access modifier... so there are only three access modifiers... docs.oracle.com/javase/tutorial/ja... also within the same package it not correct... You can omit any access modifier from a methond on an interface and it means something completely differen.tThanks for the feedback, but you are wrong
The definition in my blog says that when a keyword like public private or protected is not explicitly defined , default access modifier comes into the picture. What if in a situation when someone asks you if they don't use a any access modifier what will happen then? it can be a good interview question as well, there the only answer is default access modifier will automatically be applied.
Also the docs you mentioned says that second line means the same, I just tried to simplify it a little bit. Also in the table mentioned in the docs there is a access modifier called no modifier , it is often referred as default modifier only.
For the second part, the docs only mention that if a situation of default access modifier is there , it is only accessible from withing the same class or same package. You can crosscheck in the docs as well. Second part of your comment also doesn't seem to be entirely correct.
Thanks for taking out your time to read.
Happy learning