0

In the below code 'z' is private variable in ComplexNumber Class so when i access it using 'c2.Z' in main function of class Solution there is an error which is absolutely fine because z is a private variable and can only be accessed within class ComplexNumbers, but in sum() function of complex number class when i am accessing z of object C2 of complex number class by doing 'C2.Z' I Am not getting any error. why ?. Shouldn't i get the error when i do C2.Z in sum function because z is private variable and I am accessing it using object C2.

public class OOPS1 
{
    public static void main(String args[])
    {
        ComplexNumbers c1 = new ComplexNumbers(2);
        ComplexNumbers c2 = new ComplexNumbers(20);
        int sum = c1.sum(c2);
        print(c2.z);
        System.out.println(sum);
    }
}

class ComplexNumbers
{
    private int z;
    
    ComplexNumbers(int value)
    {
        this.z = value;
    }
    
    int sum(ComplexNumbers C2)
    {
        z = z + C2.z;
        return z;
    }
}
  • 3
    `private` variables and methods can be accessed always inside the class they are contained in, regardless of instance – Lino Jun 08 '21 at 09:01

1 Answers1

1

As per Oracle's documentation:

The private modifier specifies that the member can only be accessed in its own class

Note it specifies about class, and not instance. This means that an object from a given class can indeed access private members from other objects of the same class.

This is often useful when implementing equals for instance

julien.giband
  • 2,467
  • 1
  • 12
  • 19