#329 – A Class Can Inherit Data and Behavior from Another Class

A class can inherit data and behavior from another class.  The new class (“derived class”) automatically includes all members of the class that it inherits from (“base class”) and can also define new members.

To inherit from another class, add a ‘:’ (colon) and the name of the base class in the definition of the derived class.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public void Bark()
        {
            Console.WriteLine("{0} says woof", Name);
        }
    }

    public class Terrier : Dog
    {
        public string Attitude { get; set; }

        public void Growl()
        {
            Console.WriteLine("{0} says Grrrr", Name);
        }
    }

We can now create instances of both the Dog and the Terrier classes:

            Dog lassie = new Dog();
            lassie.Name = "Lassie";
            lassie.Age = 71;
            lassie.Bark();

            Terrier jack = new Terrier();
            jack.Name = "Jack";
            jack.Age = 17;
            jack.Attitude = "Aloof";
            jack.Bark();
            jack.Growl();