In Java, we have three access Specifiers: public, private and protected that can be used with the class members. If no access specifier is used, Java assigns a default package access to the members. Members with default access are accessible from methods in any class in the same package.
All the access specifier can be used with fields, methods and constructors but the class can only have public access specifier.
In order to understand the use of access Specifiers, let us consider the following example.
// use of public and default accesss specifier class Rectangle { public int length; // public access public int breadth; //publice access static int rectCount = 0;// default access //Constructor to initialize length and breadth Rectangle() { rectCount++;} //method to calculate area of rectangle public int area() { int rectArea; rectArea = length * breadth; return rectArea; } } class AccessSpecifer { public static void main(String[] args) { //create first rectangle object Rectangle firstRect = new Rectangle(); //accessing public members outside that Rectangle class firstRect.length = 10; firstRect.breadth = -20; System.out.println("Area of Rectangle is : "+ firstRect.area()); //Rectangle.rectCount = 5; //accessing member with default access System.out.println("Number of Object Created : "+ Rectangle.rectCount); } }