5.0 Inheritance
File Location
Right click on your solution
Go to Add > New Project and select Console App (.NET Framework)
Name it
Inheritance
Right click on the project and add an
Animal.cs
class, aBear.cs
class, aCat.cs
class, and aPolarBear.cs
class
Discussion
Inheritance is one of the key concepts to nail down in object oriented programming. Inheritance makes it easier to maintain bigger applications by defining a class based off of another class. This also allows us to reuse code functionality and speed up implementation time.
When creating a new class we can designate it to inherit the members of an existing class instead of having to completely write new data members and functions. The existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the IS-A(n) relationship. For example, mammal IS An animal, dog IS-A mammal hence dog IS-An animal as well, and so on. Lets look an example.
First lets make our base class, the class the rest of our animal classes will inherit from
We make a field that will hold the data for our
_latinName
Make a property that gets the
_latinName
and returns based on the conditionMake other properties that make up your basic animal
Make methods that make up your basic animal
Next, we make our Bear class which inherits all the properties and functions from our Animal class by adding
Bear : Animal
when defining our classAdded other properties more specific to a bear
Used override keyword to define our
StateType()
andGetMad()
methodsAdded
EatHiker()
method
Create a Cat class that inherits from Animal by using
public class Cat : Animal
Override
GetMad()
method to output"Hisss!"
We can also have a class inherit from a subclass such as having PolarBear inherit from Bear
public class PolarBear : Bear
Create some objects and values to demonstrate inheritance.
Challenge
Create a dog base class and make a few subclasses that inherit from your base class and implement it by printing some of the data to your Console.
Further Reading
Learn more about inheritance.
Next: Polymorphism
Last updated