Access Modifiers in Java

Access Modifiers in Java determine the visibility and accessibility of class members such as fields, methods, and constructors. There are four access modifiers in Java:


  1. Public: A public member can be accessed from anywhere in the program. This means that any class, regardless of its package, can access a public member. For example:

public class Car { public int speed; public void startEngine() { // code to start the engine } }


  1. Protected: A protected member can be accessed within the same class, its subclasses and classes in the same package. For example:

public class Car { protected int speed; protected void increaseSpeed() { // code to increase the speed } } class SportsCar extends Car { void goFast() { increaseSpeed(); } }

  1. Default (also known as Package-private): A default member can only be accessed within the same package. For example:

class Car { int speed; void startEngine() { // code to start the engine } }

  1. Private: A private member can only be accessed within the same class. For example:

public class Car { private int speed; public void setSpeed(int s) { speed = s; } }


Using appropriate access modifiers helps to define the level of visibility and accessibility of class members, which is important for encapsulation and data hiding. This allows for more secure and maintainable code, as you can control what is visible and accessible to the outside world.