Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private member accessible from other instances of the same class

Tags:

oop

I just noticed something that I've never realised before. It turns out that this class is valid in C#:

class Foo
{
    private string contents;

    public Foo(string str) {
        contents = str;
    }

    public void set(Foo other)
    {
        contents = other.contents;
    }
}

So different instances of the same class can access the private members of each other.

Up til now, I thought that the private members of an object could only be accessed by that object, not by other instances of the same class. It's a little suprising to find this out.

Is this the case in all common object oriented languages? It's not intuitive for me.

like image 680
Oliver Avatar asked Sep 10 '12 16:09

Oliver


People also ask

Can a class access private members of the same class?

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.

How do you make a private class member accessible in a different class?

We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class. Example: using System; using System.

Can private methods be accessed from another class?

We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.

Is private members of a class are accessible outside the class?

private - members cannot be accessed (or viewed) from outside the class. protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes.


1 Answers

This is the same as in C++ and Java: access control works on per-class basis, not on per-object basis.

In C++, Java and C# access control is implemented as a static, compile-time feature. This way it doesn't give any run time overhead. Only per-class control can be implemented that way.

like image 108
piokuc Avatar answered Oct 18 '22 17:10

piokuc