by Dinesh Thakur Category: Classes

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
     {  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);

Access Specifiers in Java with Example

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Search Content

Popular Article