W
W
whistlewars2018-07-04 10:37:04
Java
whistlewars, 2018-07-04 10:37:04

What are access specifiers for in C#/Java and other similar languages?

I'm learning C# and don't understand what's the point? You can use public everywhere and not worry, why did you add all sorts of extra specifiers and how do they help at all?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Nemiro, 2018-07-04
@whistlewars

Modifiers help you organize your code. Get rid of the potential problems of misuse of code, especially by inexperienced programmers. Sometimes I work with PHP , there are not enough internal type modifiers , I have to pervert so that others can work with the code comfortably; so that it is not possible to climb where it is not necessary and violate the logic of work; to make it look simpler on the surface than it really is.
The more complex the project, the more people working with the code, the stronger the need for order, isolation of individual sections of the project.
At the same time, if you use modifiers incorrectly and unnecessarily restrict access, then this can become a problem. You need to think carefully about the architecture to minimize the occurrence of such situations.

K
Kirill Romanov, 2018-07-04
@Djaler

To clearly separate internal implementation and external API

A
Alexey Pavlov, 2018-07-04
@lexxpavlov

class KvadrUr
{
    public double a, b, c, D, x1, x2;
    public void CalcD()
    {
        D = b*b - 4*a*c;
    }
    public void Calc()
    {
        double d  = Math.Sqrt(D);
        x1 = (-b + d)/(2*a);
        x2 = (-b - d)/(2*a);
    }
}
KvadrUr ur = new KvadrUr();
ur.a = 1;
ur.b = 2;
ur.c = -3;
ur.CalcD();
ur.Calc();
Console.WriteLine(ur.x1 + " " + ur.x2); // правильный ответ
ur.c = -4;
Console.WriteLine(ur.x1 + " " + ur.x2); // неправильный ответ - теперь дискриминант неверный!

If you make the variable D private (and call CalcD inside Calc), then this error cannot occur.
That is, restricting access to class members helps reduce the chance of error.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question