What is Default access level in Java?

Java 8Object Oriented ProgrammingProgramming

The default access level is available when no access level is specified. All the classes, data members, methods etc. which have the default access level can only be accessed inside the same package.

A program that demonstrates the default access level in Java is given as follows:

Example

 Live Demo

class Employee {
   int empno;
   String name;
   void insert(int e, String n) {
      empno = e;
      name = n;
   }
   void display() {
      System.out.println("Employee Number: " + empno);
      System.out.println("Name: " + name);
   }
}
public class Demo {
   public static void main(String[] args) {
      Employee emp = new Employee();
      emp.insert(105, "James Nortan");
      emp.display();
   }
}

Output

Employee Number: 105
Name: James Nortan

Now let us understand the above program.

The Employee class is created with data members empno, name and member functions insert() and display(). The Employee class and the data members empno, name have the default access control. A code snippet which demonstrates this is as follows:

class Employee {
   int empno;
   String name;
   void insert(int e, String n) {
      empno = e;
      name = n;
   }
   void display() {
      System.out.println("Employee Number: " + empno);
      System.out.println("Name: " + name);
   }
}

In the main() method, an object emp of class Employee is created. Then insert() method is called with parameters 105 and “James Norton”. Finally the display() method is called. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String[] args) {
      Employee emp = new Employee();
      emp.insert(105, "James Nortan");
      emp.display();
   }
}
raja
Published on 15-Feb-2019 12:06:16
Advertisements