Dziedziczenie: konstruktor bazowy i słowo base
Dziedziczenie i polimorfizm - Podstawy C# (csharp)
Tworzenie obiektu klasy pochodnej zawsze zaczyna się od konstruktora klasy bazowej.
Student(...) : base(name, age) przekazuje imię i wiek do konstruktora Person, a sam ustawia tylko swoje pole Major. Komunikaty pokazują kolejność: najpierw konstruktor bazowy, potem pochodny. Słowo base (w Javie super) pozwala też wywołać metodę klasy bazowej: base.Describe().using System;
class Person
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age)
{
Console.WriteLine("Konstruktor Person");
Name = name;
Age = age;
}
public string Describe()
{
return $"{Name}, {Age} lat";
}
}
class Student : Person
{
public string Major { get; }
public Student(string name, int age, string major) : base(name, age)
{
Console.WriteLine("Konstruktor Student");
Major = major;
}
public string DescribeStudent()
{
return base.Describe() + $", kierunek: {Major}";
}
}
class Program
{
static void Main(string[] args)
{
Student student = new Student("Kasia", 19, "Informatyka");
Console.WriteLine(student.DescribeStudent());
Console.WriteLine($"Imię z klasy bazowej: {student.Name}");
}
}Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu Podstawy C#·Zaloguj się, aby zapisać postęp na koncie.