Languages
[Edit]
PL

C# - czym jest konstruktor w programowaniu obiektowym?

10 points
Created by:
Creg
9600

Celem poniższego artykułu jest odpowiedzenie na pytanie, czym jest konstruktor w programowaniu obiektowym na przykładzie języka C#.

Odpowiedź:

Konstruktor to specyficzna metoda kasy, która jest wykonywana w momencie tworzenia obiektu, celem skonfigurowania jego pól, np. na podstawie zadanych argumentów. Konstruktory nie zwracają żadnego wyniku oraz posiadają taką samą nazwę jak nazwa klasy, w której się znajdują.

 

Przykład praktyczny

Poniżej znajduje się definicja klasy Student wraz z konstruktorem, który używając argumentu name, ustawia wewnętrzny stan klasy (ustawia jedno pole o nazwie name).

public class Program
{
    public static void Main()
    {
        Student student1 = new Student("Jan");
        Student student2 = new Student("Ewa");
        Student student3 = new Student("Krzysztof");

        // ciąg dalszy programu ...
    }
}

public class Student
{
    private string name;

    public Student(string name)  // <--- konstruktor
    {                            // <--- konstruktor
        this.name = name;        // <--- konstruktor
    }                            // <--- konstruktor
}

 

Zobacz także

  1. C# - konstruktor domyślny
  2. C# - konstruktor kopiujący

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join