Search code examples
javaencapsulation

Accessing the private Fields


I have 2 Java classes

  • JavaOne.class
  • JavaTwo.class

Both these classes are public. Inside the JavaTwo.class, I have a static class JavaThree which extends SQLiteOpenHelper. Inside JavaThree I have a private field say Gender

Public class JavaTwo{
    static class JavaThree extends SQLiteOpenHelper{
           private static final String Gender;
    }
}

How can I access the value of Gender field from JavaOne.class


Solution

  • You can access it using an accessor method or (getter() method) inside your JavaThree class, like the following:

      public String getGender() {
          return this.Gender;
      }
    

    Take a look at Accessors and Mutators for further information about their use.

    And note that if you use the final keyword with a variable it will be considered as a constant.

    Referring to Final Keyword In Java:

    If you make any variable as final, you cannot change the value of final variable(It will be constant).