-2

i have a private variable in my main class, is it possible to use it in other classes without making it a protected variable?

2 Answers2

3

No. That's the point of private vs. protected. Details in the Oracle Java member access tutorial, which also features this table:

+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
|                  **Access Levels**                 |
+−−−−−−−−−−−−−−−+−−−−−−−+−−−−−−−−−+−−−−−−−−−−+−−−−−−−+
| Modifier      | Class | Package | Subclass | World |
+−−−−−−−−−−−−−−−+−−−−−−−+−−−−−−−−−+−−−−−−−−−−+−−−−−−−+
| public        |   Y   |    Y    |    Y     |   Y   |
| protected     |   Y   |    Y    |    Y     |   N   |
| (no modifier) |   Y   |    Y    |    N     |   N   |
| private       |   Y   |    N    |    N     |   N   |
+−−−−−−−−−−−−−−−+−−−−−−−+−−−−−−−−−+−−−−−−−−−−+−−−−−−−+
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Why not use getters and setters simply to provide access to the field? – Naman Feb 23 '19 at 14:33
  • 1
    @nullpointer - You can, but that's not accessing the private members. That's providing accessors for them, which is different. – T.J. Crowder Feb 23 '19 at 14:44
  • But the *real* reason this answer isn't more in-depth is I was sure I'd find a perfect dupetarget for it, and this was largely to try to stave off the inevitable one-liner answers with a CW. Then I got sidetracked. :-D – T.J. Crowder Feb 23 '19 at 14:49
1

Private member variables are restricted to that class, however you can introduce setter and getter methods to access them. This is part of encapsulation.

An example from the URL (tutorialspoint) above, we have 3 private values with setter and getter methods that retrieve or set the value as needed:

/* File name : EncapTest.java */
public class EncapTest {
   private String name;
   private String idNum;
   private int age;

   public int getAge() {
      return age;
   }

   public String getName() {
      return name;
   }

   public String getIdNum() {
      return idNum;
   }

   public void setAge( int newAge) {
      age = newAge;
   }

   public void setName(String newName) {
      name = newName;
   }

   public void setIdNum( String newId) {
      idNum = newId;
   }
}
Moe
  • 2,672
  • 10
  • 22