Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing private method from different instance of the same class

I just came across a code.In one case i am not able to access the private members of the class using its instance (which is fine) but in other case i am able to access the private members with its different instance (belongs to the same class). Can anyone please explain me why its happening?

 class Complex {
    private double re, im; 
    public String toString() {
        return "(" + re + " + " + im + "i)";
    }
    Complex(){}

/*Below c is different instance, still it can access re,im( has a private access) 
  without any error.why? */

    Complex(Complex c) {
        re = c.re;
        im = c.im;
    }
}

public class Main {
    public static void main(String[] args) {
        Complex c1 = new Complex();
        Complex c2 = new Complex(c1);
        System.out.println(c1.re);  /* But getting an error here , 
        which is expected as re and im has a private access in Complex class.*/
    }
}
like image 442
Rohit Maurya Avatar asked Dec 06 '25 15:12

Rohit Maurya


1 Answers

You can access private members from any code block that is defined in the same class. It doesn't matter what the instance is, or even if there is any instance (the code block is in a static context).

But you cannot access them from code that is defined in a different class.

Your first reference is in the same class, Complex, which is why it works. And the second is in a different class, Main, which is why it doesn't work.

like image 110
Ville Oikarinen Avatar answered Dec 09 '25 18:12

Ville Oikarinen