Q:

Java program to create members with access modifier

belongs to collection: Java Class and Object Programs

0

Java program to create members with access modifier

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Program/Source Code:

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 num1num2 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Class and Object Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to create a singleton class... >>
<< Java program to create members with private access...