Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Default Access Specifier in Java

Last Updated on December 28, 2023 by Ankit Kochar

In the world of Java programming, understanding access control is crucial for building robust and maintainable software. The default access specifier plays a pivotal role in regulating the visibility of classes, methods, and fields within a package. Unlike public, private, and protected access specifiers, the default access specifier (also known as package-private) does not involve the use of a keyword. Instead, when no access specifier is explicitly specified, Java assigns the default access level. This default setting restricts the visibility of the element to only classes within the same package, offering a balance between encapsulation and collaboration.

Access Specifier Within Class Within Package Outside Package by Subclass only Outside Package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

In this article, we will focus on the default access specifier in Java. The default access specifier in Java is used when no access modifier is specified for a class, method, or variable. It is also known as package-private because it restricts access to only within the same package. Let’s understand this concept in detail with examples and explanations.

Default Access Specifier in Java: Usage in Class

When we declare a class without any access modifier/ access specifier, it is considered as default or package-private. Here is the general syntax for declaring a default package.

package prepbytes;

class MyClass {
   // class members
}

Here, MyClass is declared without any access modifier. Therefore, it is considered as default or package-private. This means that MyClass can only be accessed within the same package, i.e., prepbytes.

Examples of Default Access Specifier in Java: Usage in Classes

Let’s see examples to understand the concept of Default Access Specifier in Classes in detail.

Example 1: Accessing the Default Class Within the Package
This example demonstrates accessing the Default Class within the same Package.

Code:

package prepbytes;


class MyClass {
    public void myMethod() {
       System.out.println("This is my method.");
    }
 }
 
 public class Main {
    public static void main(String[] args) {
       MyClass obj = new MyClass();
       obj.myMethod(); // calling a public method of MyClass
    }
 }

Output:

This is my method.

Explanation:
In this example, we have two classes: MyClass and Main. MyClass is declared as default, which means it can only be accessed within the same package, i.e., “prepbytes”. Main is declared as public, which means it can be accessed from anywhere.

We have defined a public method named myMethod() in MyClass, which prints a message to the console. In the main method of the Main class, we have created an object of MyClass and called the myMethod() method on it. Since myMethod() is declared public, it can be accessed from anywhere, including outside the package.

Example 2: Accessing the Default Class Outside the Package
Now let’s see what happens when we try to access MyClass from outside the package:

Code:

package package2;
import prepbytes.*;


public class AnotherClass {
    public static void main(String[] args) {
       MyClass obj = new MyClass(); // error: MyClass has default access in prepbytes
       obj.myMethod();
    }
 } 

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
        The type MyClass is not visible
        The type MyClass is not visible
        The type MyClass is not visible

        at package2.AnotherClass.main(AnotherMain.java:6)

Explanation:
In this example, we have a class named AnotherClass, which is declared in a different package, i.e.,package2. We are trying to create an object of MyClass in this class, but we get a compilation error because MyClass has default access and can only be accessed within the same package i.e., prepbytes.

Default Access Specifier in Java: Usage in Methods

When we declare a method without any access modifier, it is also considered as default or package-private. Here is the general syntax for the Default Method.

package prepbytes;

class MyClass {
   void myMethod() {
      System.out.println("This is my method.");
   }
}

Here, we have defined a method named myMethod() in MyClass without any access modifier. Therefore, it is considered as default or package-private. This means that myMethod() can only be accessed within the same package, i.e., prepbytes.

Examples of Default Access Specifier in Java: Usage in Methods

Let’s see examples for a better understanding of Default Methods in Java.

Example 1: Accessing the Default Methods Within the Package
This example demonstrates accessing the Default Methods within the same Package.

Code:

package prepbytes;


class MyClass {
   void myMethod() {
      System.out.println("This is my method.");
   }
}


public class Main {
   public static void main(String[] args) {
      MyClass obj = new MyClass();
      obj.myMethod(); // calling a default method of MyClass
   }
}

Output:

This is my method.

Explanation:
In this example, we have two classes: MyClass and Main. MyClass has a method named myMethod() which is declared as default, and Main is declared as public.

In the main method of the Main class, we have created an object of MyClass and called the myMethod() method on it. Since myMethod() is declared as default, it can only be accessed within the same package, i.e., prepbytes.

Example 2: Accessing the Default Method Outside the Package
Now let’s see what happens when we try to access myMethod() from outside the package.

Code:

package package2;


import prepbytes.MyClass;


public class AnotherClass {
   public static void main(String[] args) {
      MyClass obj = new MyClass();
      obj.myMethod(); // error: myMethod() has default access in prepbytes.MyClass
   }
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
        MyClass cannot be resolved to a type
        MyClass cannot be resolved to a type

        at package2.AnotherClass.main(AnotherMain.java:7)

Explanation:
In this example, we are trying to access myMethod() from AnotherClass, which is declared in a different package, i.e., package2. We are getting a compilation error because myMethod() has default access and can only be accessed within the same package.

Default Access Specifier in Java: Usage in Variables

When we declare a variable without any access modifier, it is also considered as default or package-private. Here is how we declare variables with default access specifier in java.

package prepbytes;

class MyClass {
   int myVariable = 10;
}

We have defined a variable named myVariable in MyClass without any access modifier. Therefore, it is considered as default or package-private. This means that myVariable can only be accessed within the same package, i.e., prepbytes.

Examples of Default Access Specifier in Java: Usage with Variables

Let’s see examples for a better understanding of Variables with Default Access Specifier in Java.

Example 1: Accessing the Default Variables Within the Package
This example demonstrates accessing the Default Variables within the same Package.

Code:

package prepbytes;


class MyClass {
   int myVariable = 10;
}


public class Main {
   public static void main(String[] args) {
      MyClass obj = new MyClass();
      System.out.println(obj.myVariable); // accessing a default variable of MyClass
   }
}

Output:

10

Explanation:
In this example, we have two classes: MyClass and Main. MyClass has a variable named myVariable which is declared as default, and Main is declared as public.

In the main method of Main class, we have created an object of MyClass and accessed the myVariable variable on it. Since myVariable is declared as default, it can only be accessed within the same package, i.e., prepbytes and we get the expected output on the screen.

Example 2: Accessing the Default Variables Outside the Package
Now let’s see what happens when we try to access myVariable from outside the package.

Code:

package package2;


import prepbytes.*;


public class AnotherMain {
    public static void main(String[] args) {
       MyClass obj = new MyClass();
       System.out.println(obj.myVariable); // error: myVariable has default access in com.example.MyClass
    }
 }

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
        The type MyClass is not visible
        The type MyClass is not visible
        The type MyClass is not visible

        at package2.AnotherMain.main(AnotherMain.java:7)

Explanation:
In this example, we are trying to access myVariable from AnotherClass, which is declared in a different package, i.e., package2. We are getting a compilation error because myVariable has default access and can only be accessed within the same package.

Advantages of Default Access Specifier in Java

The default access Specifier in Java provides several advantages:

  • The usage of the Default Access Specifier in Java restricts access to the package level. It helps to hide the implementation details from the outside world and only necessary information is exposed.
  • The default access Specifier in Java provides a simpler way for restricting access to the package level without the use of any keyword.
  • The default access specifier in Java provides faster performance than the other access modifiers because there is no need to check for access levels across different packages.
  • The usage of the Default Access Specifier in Java enhances security as it helps in preventing unauthorized access to the package-level classes and the methods.

Conclusion
In conclusion, the default access specifier in Java is a subtle yet powerful mechanism for controlling the visibility of classes, methods, and fields within a package. By limiting access to only classes within the same package, Java promotes encapsulation and modular design, facilitating the creation of well-organized and maintainable code. As developers, it is essential to be mindful of access specifiers, including the default access level, to strike the right balance between information hiding and collaboration in our Java projects.

Frequently Asked Questions (FAQs) Related to Default Access Specifier in Java

Some Frequently Asked Questions on Default Access Specifiers in Java are listed below.

Q1: What is the default access specifier in Java?
A1:
The default access specifier, also known as package-private, is the access level assigned when no access specifier is explicitly specified. It restricts the visibility of classes, methods, and fields to only classes within the same package.

Q2: How does the default access specifier differ from other access specifiers?
A2:
Unlike public, private, and protected access specifiers, the default access specifier does not use a keyword. It automatically applies when no access specifier is specified, and it limits visibility to classes within the same package.

Q3: Can I use the default access specifier for methods and fields?
A3:
Yes, the default access specifier can be applied to methods and fields. When no access specifier is explicitly mentioned, Java assigns the default access level, restricting access to classes within the same package.

Q4: Why is encapsulation important in Java?
A4:
Encapsulation is essential in Java to promote information hiding and protect the internal details of a class. It enhances code modularity, reduces complexity, and facilitates better maintenance by preventing external classes from directly accessing internal implementation details.

Q5: How can I control access across different packages in Java?
A5:
To control access across different packages, you can use the public, private, protected, or package-private (default) access specifiers. Public allows access from any package, private restricts access to the declaring class, protected allows access within the same package and subclasses, and default restricts access to the same package.

Leave a Reply

Your email address will not be published. Required fields are marked *