16.3. Object Orientation in C#: Inheritance and Polymorphism
Page 19 | Listen in audio
Object orientation is one of the fundamental principles of programming, and it is especially important when working with Unity and C#. In this chapter, we will discuss two main concepts of object orientation in C#: inheritance and polymorphism.
16.3.1 Inheritance
Inheritance is one of the pillars of object orientation. It allows you to create a new class that reuses, extends, and modifies behavior that is defined in another class. The class whose members are inherited is called the base class, and the class that inherits these members is called the derived class.
In C#, inheritance is defined using the ':' symbol. For example, if we have a base class 'Animal' and we want to create a derived class 'Dog', we would do it like this:
public class Animal { public void Eat() { Console.WriteLine("Eating..."); } } public class Dog : Animal { public void Bark() { Console.WriteLine("Barking..."); } }
Here, 'Dog' inherits the 'Eat()' method from 'Animal', and also defines a new 'Bark()' method. So, an object of class 'Dog' can call both methods.
16.3.2 Polymorphism
Polymorphism is another pillar of object orientation. It allows you to treat objects of a derived class as objects of its base class, which can be useful for writing more generic and reusable code.
Polymorphism in C# is implemented through virtual methods in the base class and override methods in the derived class. A virtual method is a method that can be overridden in a derived class. To create a virtual method, you use the 'virtual' keyword in the method declaration in the base class:
public class Animal { public virtual void MakeSound() { Console.WriteLine("The animal makes a sound"); } }
Then in the derived class you can override this method using the 'override' keyword:
public class Dog : Animal { public override void MakeSound() { Console.WriteLine("The dog barks"); } }
Now, if you create an object of the 'Dog' class and call the 'MakeSound()' method, it will print "The dog barks". But if you treat this object as an 'Animal' and call 'MakeSound()', it will still print "The dog barks", because the method has been overridden.
In summary, inheritance and polymorphism are fundamental concepts of object-oriented programming in C#. They allow you to write more reusable and generic code, which is especially useful when working with Unity. In the next chapter, we'll explore how these concepts can be applied to create more complex and interesting games.
Now answer the exercise about the content:
What are the two main concepts of object orientation in C# discussed in the text?
You are right! Congratulations, now go to the next page
You missed! Try again.
Next page of the Free Ebook: