×

Java Programs

Java Practice

Java program to create members with access modifier

Demonstrate the example of create members with access modifier in Java.
Submitted by Nidhi, on March 16, 2022

Problem statement

In this program, we will create two members without specifying any modifier and access them inside or outside the class.

Note: If we do not specify any access modifier then by default it is known as default modifier. These types of members can be accessed outside the class but can not be accessed outside the package.

Java program to create members with access modifier

The source code to create members with access modifier is given below. The given program is compiled and executed successfully.

// Java program to create members 
// with access modifier

class Demo {
  int num1 = 10;
  int num2 = 20;

  void printValues() {
    System.out.printf("Num1: %d\n", num1);
    System.out.printf("Num2: %d\n", num2);

    num1 = 30;
    num2 = 40;
  }
}

public class Main {
  public static void main(String[] args) {
    Demo d = new Demo();

    d.printValues();

    // Default members of the Demo class can be 
    // accessed outside the class.
    System.out.printf("Num1: %d\n", d.num1);
    System.out.printf("Num2: %d\n", d.num2);
  }
}

Output

Num1: 10
Num2: 20
Num1: 30
Num2: 40

Explanation

In the above program, we created two classes Demo and Main. The Demo class contains two members num1, num2 without any access modifier. And, printed the value of members using the printValues() method and also modify the values of members.

The Main class contains a static method main(). The main() is an entry point for the program. Here, we created the object of Demo class and called printValues() method to values of num1 and num2. After that, we printed the values of num1 and num2 directly.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.