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;
}
}