#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;

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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: