Can we access private variable outside of the class in Java?

In this tutorial, we are going to learn about the property of private variable in java. We will learn can we access it outside of the class in Java? By Preeti Jain Last updated : January 14, 2024

Private variable in Java

Private variable can declare with the private keyword.

Can we access private variable outside of the class in Java?

The simple answer is NO. You cannot access private variables outside of the class.

Example to access Java private variables inside a class

In the below example, we will see we can access private variable in the same class.

public class Main {
  /* Declare private variable named x */
  private int x;

  /* Define constructor for private 
  variable initialization */
  Main(int x) {
    this.x = x;
  }

  /* Define method to print value of variable x */
  public void privateVariableAccess() {
    System.out.println("value of x is :" + x);
  }

  /* Main method definition */
  public static void main(String[] args) {
    /* create Main 
    object and pass the value of private variable */
    Main cpvaitsc = new Main(10);
    /* call Main method 
    with the help of Main 
    object */
    cpvaitsc.privateVariableAccess();
  }
}

Output

value of x is :10

Example to access Java private variables outside the class

In the below example, we will see we cannot access private variable outside the class.

public class Main {
  /* Declare private variable named x */
  private int x = 10;

  /* Define method to print value of variable x */
  public void privateVariableAccess() {
    System.out.println("value of x is :" + x);
  }

  public static void main(String[] args) {}
}

class OutsideClass extends Main {
  public static void main(String[] args) {
    Main cpvaitdc = new Main();
    /* x is variable of Main class 
    so we can call x variable with the help of 
    Main object */
    System.out.println(cpvaitdc.x);
  }
}

Output

Main.java:19: error: x has private access in Main
    System.out.println(cpvaitdc.x);
                               ^
1 error


Comments and Discussions!

Load comments ↻





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