Inheritance and over riding methods – c#

Inheritance allows one class to be expanded on in further classes. The protected method/variables in the base class is accessible to the inherited classes, but the private method/variables are not.

Here is a very basic inheritance

using System;
 
namespace inheritance
{
 
	class firstClass
	{
		public void printFirstOut()
		{
			Console.WriteLine("Hi from the first class");
		}
 
	}
 
	class secondClass : firstClass
	{
		public void printSecondOut()
		{
			Console.WriteLine("Hi from second class");
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			secondClass sec = new secondClass();
			// can still call the first class method
			sec.printFirstOut();
 
			// and also the second class method of course
			sec.printSecondOut();
 
			firstClass first = new firstClass();
			// can print out the first class method
			first.printFirstOut();
 
			// but first does not have knowledge of the printSecondOut() method
			// because it is not linked. Error below.
//			first.printSecondOut();
			// Description=Type `inheritance.firstClass' does not contain a definition for `printSecondOut' 
			// and no extension method `printSecondOut' of type `inheritance.firstClass' 
			// could be found (are you missing a using directive or an assembly reference?)(CS1061)]
		}
	}
}

output would be

Hi from the first class
Hi from second class
Hi from the first class

Over riding of methods from the base class can happen to make a version 2 of a class as such.

The printClassName() method below is override’d in the secondClass and it requires to have the word ‘new’ because then that tells the compiler to over ride the method in the secondclass, it may come back with a warning in the compiling of this project to say that there is a same method name in the inherited class.

using System;
 
namespace inheritance
{
 
	class firstClass
	{
		public void printClassName()
		{
			Console.WriteLine("FirstClass");
		}
	}
 
	class secondClass : firstClass
	{
		new public void printClassName()
		{
			Console.WriteLine("SecondClass");
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			firstClass first = new firstClass();
			first.printClassName();
 
			secondClass sec = new secondClass();
			sec.printClassName();
		}
	}
}

output would be

FirstClass
SecondClass

Leave a Reply

Your email address will not be published. Required fields are marked *