Inheritance
Today we learn how to do inheritance in C#. In programming when a class uses objects and properties of another class then it is known as inheritance. So today we will cover following topics.
- How to create a class.
- How to create a super and sub class.
- Access base class from derived class.
- Inherit child class from base class.
- How to protect base class properties.
So first as we now C# is a pure object oriented language and it uses classes to execute a function and to understand the concept of inheritance we must have to know how to create a class in C#.
Code:
1 2 3 4 |
public class city{ public int pobox_no; public void places(){ } } |
Above is the class name city having one attribute and one function or method. Now let’s take an example how to create a super and sub class.
Example of Inheritance in C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
usin System; public class SuperClass{ //create constructor public SuperClass(){ Console.WriteLine("Super class Constructor."); } public void output() { Console.WriteLine("Super class function here."); } } public class ChildClass : SuperClass{ public ChildClass(){ Console.WriteLine("Sub class Constructor."); } public static void Main() { ChildClass obj = new ChildClass(); obj.out(); } } |
To access base class in child class we must have to make sure that the variable or method we want to access is public or protected, and then we simply call this as we call members of the same class.
To inherit child class from super class “:” colon is used.
Like
public class derived : public base{ }
To protect base class function and attributes we have to define their scope to private so that they are not visible outside the class even to that one which inherits that class and this process is called encapsulation.
To learn more about inheritance and its types
How derived Class access Base Class and how to handle constructors?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System; public class BaseClass{ string name; public BaseClass() { Console.WriteLine("Base class Constructor here."); } public ChildClass(string newname) { name = newname; Console.WriteLine(name); } public void show(){ Console.WriteLine("I'm a Parent Class."); } } public class ChildClass : BaseClass{ public ChildClass() : base("override from child class"){ Console.WriteLine("child class constructor."); } public new void show() { base.show(); Console.WriteLine("child class executing."); } public static void Main() { ChildClass obj = new ChildClass(); obj.show(); ((mainclass)obj).show(); } } |