Поширені Модифікатори Доступу
Ви, ймовірно, вже знайомі з ключовим словом public
. Це модифікатор доступу, який визначає, звідки можна отримати доступ до певного класу, методу або поля.
Аналогічно існують терміни, такі як private
та protected
. Обидва ці терміни використовуються для визначення доступності методу або поля.
Якщо ви пишете public
перед класом, це просто робить клас доступним з різних частин (файлів) програми. Вам не потрібно детально розглядати цей аспект, оскільки він виходить за межі цієї глави.
Якщо ви вказуєте метод або поле як public
, ви фактично робите цю властивість класу доступною з будь-якої частини коду через об'єкт:
index.cs
1234567891011121314151617181920212223using System; public class Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } class ConsoleApp { static void Main() { Point p = new Point(7, 9); // We can directly access 'public' fields of an object using the dot '.' symbol Console.WriteLine(p.x); Console.WriteLine(p.y); } }
Якщо ви не бажаєте, щоб поле або метод об'єкта були доступні поза межами класу, можна просто зробити їх private
:
index.cs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748using System; class Point { public int x; public int y; private double magnitude; public Point(int x, int y) { this.x = x; this.y = y; this.magnitude = calculateMagnitude(); } // A private method can only be used inside the class. // Trying to use a private method outside the class might result in a compilation error. private double calculateMagnitude() { // Math.Sqrt() is the square root function. return Math.Sqrt(x * x + y * y); } // Sometimes, to be able to access data from a private field, we make public methods // which specifically retrieve the value of that field. Such methods are called "getters", // and such fields are called "read-only" fields as we can access their data but cannot modify it from outside the class. public double getMagnitude() { return magnitude; } } class ConsoleApp { static void Main() { Point p = new Point(7, 9); // Correct Console.WriteLine(p.getMagnitude()); // Error Console.WriteLine(p.calculateMagnitude()); // Error Console.WriteLine(p.magnitude); } }
Важливо зазначити, що приватні поля та методи не успадковуються похідними класами:
index.cs
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253using System; class Point { public int x; public int y; private double magnitude; public Point(int x, int y) { this.x = x; this.y = y; this.magnitude = calculateMagnitude(); } private double calculateMagnitude() { // Math.Sqrt() is the square root function. return Math.Sqrt(x * x + y * y); } public double getMagnitude() { return magnitude; } } class Point3D : Point { public int z; // The 'base(x, y)' part simply calls the constructor of the 'Point' class with 'x' and 'y' values. // This will be more thoroughly explained in the later section. public Point3D(int x, int y, int z) : base(x, y) { this.z = z; // Error calculateMagnitude(); } } class ConsoleApp { static void Main() { Point3D p = new Point3D(5, 7, 9); // Correct according to rules of language, however note that it will give the magnitude of x and y excluding z (for a 2D point) so logically the result will be wrong Console.WriteLine(p.getMagnitude()); } }
Щоб зробити поле або метод недоступним ззовні класу, але доступним для дочірніх класів, використовуйте ключове слово protected
:
index.cs
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950using System; class Point { public int x; public int y; protected double magnitude; public Point(int x, int y) { this.x = x; this.y = y; this.magnitude = calculateMagnitude(); } protected double calculateMagnitude() { // Math.Sqrt() is the squareroot function. return Math.Sqrt(x * x + y * y); } public double getMagnitude() { return magnitude; } } class Point3D : Point { public int z; public Point3D(int x, int y, int z) : base(x, y) { this.z = z; // No Error Now calculateMagnitude(); } } class ConsoleApp { static void Main() { Point3D p = new Point3D(5, 7, 9); Console.WriteLine(p.getMagnitude()); } }
Іноді для доступу до приватних атрибутів класу створюють публічні методи, які називають геттерами. Метод getMagnitude
є прикладом геттера. Це гарантує, що поле можна лише читати, але не змінювати, роблячи цей атрибут тільки для читання.
Якщо для члена класу не вказано модифікатор доступу, за замовчуванням він вважається private
.
1. Який модифікатор доступу дозволяє члену бути доступним лише всередині класу, в якому він визначений?
2. Як зробити атрибут класу недоступним ззовні?
3. Який ефективний спосіб отримати значення приватних полів ззовні класу?
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you explain the difference between public, private, and protected with examples?
Why would I use getters instead of making a field public?
Are there any best practices for choosing between these access modifiers?
Awesome!
Completion rate improved to 2.04
Поширені Модифікатори Доступу
Свайпніть щоб показати меню
Ви, ймовірно, вже знайомі з ключовим словом public
. Це модифікатор доступу, який визначає, звідки можна отримати доступ до певного класу, методу або поля.
Аналогічно існують терміни, такі як private
та protected
. Обидва ці терміни використовуються для визначення доступності методу або поля.
Якщо ви пишете public
перед класом, це просто робить клас доступним з різних частин (файлів) програми. Вам не потрібно детально розглядати цей аспект, оскільки він виходить за межі цієї глави.
Якщо ви вказуєте метод або поле як public
, ви фактично робите цю властивість класу доступною з будь-якої частини коду через об'єкт:
index.cs
1234567891011121314151617181920212223using System; public class Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } class ConsoleApp { static void Main() { Point p = new Point(7, 9); // We can directly access 'public' fields of an object using the dot '.' symbol Console.WriteLine(p.x); Console.WriteLine(p.y); } }
Якщо ви не бажаєте, щоб поле або метод об'єкта були доступні поза межами класу, можна просто зробити їх private
:
index.cs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748using System; class Point { public int x; public int y; private double magnitude; public Point(int x, int y) { this.x = x; this.y = y; this.magnitude = calculateMagnitude(); } // A private method can only be used inside the class. // Trying to use a private method outside the class might result in a compilation error. private double calculateMagnitude() { // Math.Sqrt() is the square root function. return Math.Sqrt(x * x + y * y); } // Sometimes, to be able to access data from a private field, we make public methods // which specifically retrieve the value of that field. Such methods are called "getters", // and such fields are called "read-only" fields as we can access their data but cannot modify it from outside the class. public double getMagnitude() { return magnitude; } } class ConsoleApp { static void Main() { Point p = new Point(7, 9); // Correct Console.WriteLine(p.getMagnitude()); // Error Console.WriteLine(p.calculateMagnitude()); // Error Console.WriteLine(p.magnitude); } }
Важливо зазначити, що приватні поля та методи не успадковуються похідними класами:
index.cs
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253using System; class Point { public int x; public int y; private double magnitude; public Point(int x, int y) { this.x = x; this.y = y; this.magnitude = calculateMagnitude(); } private double calculateMagnitude() { // Math.Sqrt() is the square root function. return Math.Sqrt(x * x + y * y); } public double getMagnitude() { return magnitude; } } class Point3D : Point { public int z; // The 'base(x, y)' part simply calls the constructor of the 'Point' class with 'x' and 'y' values. // This will be more thoroughly explained in the later section. public Point3D(int x, int y, int z) : base(x, y) { this.z = z; // Error calculateMagnitude(); } } class ConsoleApp { static void Main() { Point3D p = new Point3D(5, 7, 9); // Correct according to rules of language, however note that it will give the magnitude of x and y excluding z (for a 2D point) so logically the result will be wrong Console.WriteLine(p.getMagnitude()); } }
Щоб зробити поле або метод недоступним ззовні класу, але доступним для дочірніх класів, використовуйте ключове слово protected
:
index.cs
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950using System; class Point { public int x; public int y; protected double magnitude; public Point(int x, int y) { this.x = x; this.y = y; this.magnitude = calculateMagnitude(); } protected double calculateMagnitude() { // Math.Sqrt() is the squareroot function. return Math.Sqrt(x * x + y * y); } public double getMagnitude() { return magnitude; } } class Point3D : Point { public int z; public Point3D(int x, int y, int z) : base(x, y) { this.z = z; // No Error Now calculateMagnitude(); } } class ConsoleApp { static void Main() { Point3D p = new Point3D(5, 7, 9); Console.WriteLine(p.getMagnitude()); } }
Іноді для доступу до приватних атрибутів класу створюють публічні методи, які називають геттерами. Метод getMagnitude
є прикладом геттера. Це гарантує, що поле можна лише читати, але не змінювати, роблячи цей атрибут тільки для читання.
Якщо для члена класу не вказано модифікатор доступу, за замовчуванням він вважається private
.
1. Який модифікатор доступу дозволяє члену бути доступним лише всередині класу, в якому він визначений?
2. Як зробити атрибут класу недоступним ззовні?
3. Який ефективний спосіб отримати значення приватних полів ззовні класу?
Дякуємо за ваш відгук!