Search code examples
javaclassprivatecomparable

What does it mean to say the keyword "private" is private at the class level?


A source I am reading says that the keyword private means a method or variable is private at the class level, not the object level.

Meaning in a chunk of code like this:

public class Weight2 implements Comparable<Weight2>
{
   private int myPounds, myOunces;

   public Weight2()
   {
      myPounds = myOunces = 0;
   }
   public Weight2(int x, int y)
   {
      myPounds = x;
      myOunces = y; 
   }

   public int compareTo(Weight2 w)
   {
      if(myPounds<w.myPounds)
         return -1;
      if(myPounds>w.myPounds)
         return 1;
      if(myOunces<w.myOunces)
         return -1;
      if(myOunces>w.myOunces)
         return 1;
      return 0;
   }
}

A Weight2 object can access the private fields of a different weight2 object without an accessor method... but rather by just saying w.myPounds.

CLARIFICATION:

I want to know from where objects can access a different object's private data. Is it only from within the class? Or could this be done from a driver program?


Solution

  • A source I am reading says that the keyword private means a method or variable is private at the class level, not the object level.

    I don't know your source. It is not wrong but it is not clear either.

    You could refer to the JLS that bring this information about the private modifier :

    Chapter 6. Names

    6.6.1. Determining Accessibility

    ... the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

    About :

    So what I mean to ask is, can objects of the same type access each other's private fields without accessor methods?

    Indeed.

    And it is rather consistent with the specification.
    It doesn't restrict the access to private members to only the current instance.
    So, you may consider that this limitation doesn't exist and so you can invoke private method for current instance or any variable referencing the current class.
    And it is of course true in static as in instance contexts.


    As a side note, you should also take into consideration the level access: class and instance.
    The private static modifiers means a method or variable is private at the class level. So, you don't need any instance to refer it.
    While the private modifier (without the static modifier) means a method or variable is private at the instance level. So you need an instance to refer it.