C Sharp for Beginners/Inheritance

From Wikibooks, open books for an open world
Jump to navigation Jump to search

As this is about getting started programming, we don't want to confuse you with too much complicated stuff.

You may sometimes see classes declared like this:

class MyClass : Form 	
{
	...//
}

instead of just like this

class MyClass
{
	...//
}

People Inheritance

It is common for You to inherit characteristics from your parents. You may have your Mother’s way of talking or your Father’s nose. This doesn't mean you are identical to your Parents, but certain characteristics come "built in" when you’re born.

Code Inheritance

When we write code, it could be useful to inherit a whole bunch of abilities from an existing class. Lets go with an example. There are two defined classes “Animal” and “Bird”, but the “Bird” class inherits from the Animal class.

class Animal
{
	public string kindOfAnimal;
	public string name;
	....
	
}

class Bird : Animal	// “Bird” class inherits from “Animal” class
{
	public string featherColor;
	
}

In real world, a bird is a kind of animal, but it has some characteristics that don’t apply to all animals. So it makes sense for a Bird class to have all the characteristics of an Animal as well as some extra ones. In this case, we’ve identified one special field for birds only – featherColor. We're really saying "I'm defining a new class called ‘Bird’ but it must inherit everything from the “Animal” class too.";

When to Use Inheritance

Inheritance is best used in cases where what you're trying to achieve can mostly be done by an existing class and you just want to extend it or customize it. In the following example, the class "Guitarist" inherits three fields from the class "Musician" and adds two fields of its own. The colon “:” is the part that tells the computer to make the new class (Guitarist) inherit from the class written to the right of the colon.

public class Musician
{
	public string name;
	public int ageInYears;
        ....\\
}

public class Guitarist : Musician
{
	public string guitarType;
	public string guitarBrand;
}

Guitarist g = new Guitarist();
g.name = "JOHN ABC";
g.ageInYears = 25;
g.guitarType = Acoustic;
g.guitarBrand = Gibson;

When we create an instance of a “Guitarist”, we can immediately address the fields of both a Musician and a Guitarist (as long as they’re not private).