For those who are already programming in C#, using Inheritance for class level reusability and Polymorphism for processing objects differntly depending on their class, become quite useful.
Inheritance
One of the key concepts of Object Oriented Programming is nothing but inheritance. By using the concept of inheritance, it is possible to create a new class from an existing one and add new features to it. Thus inheritance provides a mechanism for class level re usability. The new programming language C# also supports inheritance. The syntax of inheritance is very simple and straightforward.
class Base
{
}
class Derived : Base
{
}
The operator ‘:’is used to indicate that a class is inherited from another class. Remember that in C#, a derived class can’t be more accessible than it’s base class. That means that it is not possible to declare a derived class as public, if it inherits from a private class. For example the following code will generate a compile time error.
class Base
{
}
public class Derived : Base
{
}
In the above case the Base class is private. We try to inherit a public class from a private class.
Let us see a concrete example.
In this case Derived class inherits public members of the Base class x,y and Method(). The objects of the Derived class can access these inherited members along with its own member z.
// Inheritance
// Author: rajeshvs@msn.com
using System;
class Base
{
public int x = 10;
public int y = 20;
public void Method()
{
Console.WriteLine("Base Method");
}
}
class Derived : Base
{
public int z = 30;
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
Console.WriteLine("{0},{1},{2}",d1.x,d1.y,d1.z); // displays 10,20,30
d1.Method();// displays 'Base Method'
}
}
Inheritance & Access Modifiers
A derived class inherits every thing from the base class except constructors and destructors. The public members of the Base class becomes the public members of the Derived class also. Similarly the protected members of the base class become protected members of the derived class and internal member becomes internal members of the derived class. Even the private members of the base class are inherited to the derived class, even though derived class can’t access them.
Inheritance & Data Members
We know all base class data members are inherited to the derived, but their accessibility remains unchanged in the derived class. For example in the program given below
// Inheritance : datamebers
// Author: rajeshvs@msn.com
using System;
class Base
{
public int x = 10;
public int y = 20;
}
class Derived : Base
{
public int z = 30;
public void Sum()
{
int sum = x+y+z;
Console.WriteLine(sum);
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Sum();// displays '60'
}
}
Here class Derived have total three data members, two of them are inherited from the Base class.
In C#, even it is possible to declare a data member with the same name in the derived class as shown below. In this case, we are actually hiding a base class data member inside the Derived class. Remember that, still the Derived class can access the base class data member by using the keyword base.
// Inheritance : datameber hiding
// Author: rajeshvs@msn.com
using System;
class Base
{
public int x = 10;
public int y = 20;
}
class Derived : Base
{
public int x = 30;
public void Sum()
{
int sum = base.x+y+x;
Console.WriteLine(sum);
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Sum();// displays '60'
}
}
But when we compile the above program, the compiler will show a warning, since we try to hide a Base class data member inside the Derived class. By using the keyword new along with the data member declaration inside the Derived class, it is possible to suppress this compiler warning.
The keyword new tells the compiler that we are trying to explicitly hiding the Base class data member inside the Derived class. Remember that we are not changing the value of the Base class data member here. Instead we are just hiding or shadowing them inside the Derived class. However the Derived class can access the base class data member by using the base operator.
// Inheritance : datameber hiding with new
// Author: rajeshvs@msn.com
using System;
class Base
{
public int x = 10;
public int y = 20;
}
class Derived : Base
{
public new int x = 30;
public void Sum()
{
int sum = base.x+y+x;
Console.WriteLine(sum);
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Sum();// displays '60'
}
}
Inheritance & Member Functions
What ever we discussed for data members are valid for member functions also. A derived class member function can call the base class member function by using the base operator. It is possible to hide the implementation of a Base class member function inside a Derived class by using the new operator.
When we declare a method in the Derived class with exactly same name and signature of a Base class method, it is known as ‘method hiding’. But during the compilation time, the compiler will generate a warning. But during run-time the objects of the Derived class will always call the Derived class version of the method. By declaring the derived class method as new, it is possible to suppress the compiler warning.
// Inheritance : Method hiding without new operator
// Author: rajeshvs@msn.com
using System;
class Base
{
public void Method()
{
Console.WriteLine("Base Method");
}
}
class Derived : Base
{
public void Method()
{
Console.WriteLine("Derived Method");
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Method(); // displays 'Derived Method'
}
}
Uses of new and base operators are given in the following program.
// Inheritance : Method hiding without new operator
// Author: rajeshvs@msn.com
using System;
class Base
{
public void Method()
{
Console.WriteLine("Base Method");
}
}
class Derived : Base
{
public new void Method()
{
Console.WriteLine("Derived Method");
base.Method();
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Method(); // displays 'Derived Method' followed by 'Base Method'
}
}
Inheritance & Constructors
The constructors and destructors are not inherited to a Derived class from a Base class. However when we create an object of the Derived class, the derived class constructor implicitly call the Base class default constructor. The following program shows this.
// Inheritance : constructor
// Author: rajeshvs@msn.com
using System;
class Base
{
public Base()
{
Console.WriteLine("Base class default constructor");
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 =new Derived();// Displays 'Base class default constructor'
}
}
Remember that the Derived class constructor can call only the default constructor of Base class explicitly. But they can call any Base class constructor explicitly by using the keyword base.
// Inheritance : constructor chaining
// Author: rajeshvs@msn.com
using System;
class Base
{
public Base()
{
Console.WriteLine("Base constructor1");
}
public Base(int x)
{
Console.WriteLine("Base constructor2");
}
}
class Derived : Base
{
public Derived() : base(10)// implicitly call the Base(int x)
{
Console.WriteLine("Derived constructor");
}
}
class MyClient
{
public static void Main()
{
// Displays 'Base constructor2 followed by 'Derived Constructor''
Derived d1 = new Derived();
}
}
Note that by using base() the constructors can be chained in an inheritance hierarchy.
Polymorphism & Virtual Methods
A virtual method in C# specifies an implementation of a method that can be polymorphicaly overridden derived method. A non-virtual method can’t be polymorphically override in a Derived class.
A virtual method can be declared by using the keyword virtual as follows.
class Base
{
public virtual void Method()
{
}
}
When we declare a virtual method, it must contain a method body. Other wise the compiler will generate an error. Remember that, since virtual methods are used for achieving polymorphism and since polymorphism works only with objects, it not possible to declare a static method as virtual in C#. Similarly the private methods are also not possible to declare virtual, since they can’t override inside a derived class.
In C#, it is not necessary to override a Base class virtual method inside a Derived class.
The following program will work absolutely correct.
// Inheritance : Virtual methods
// Author: rajeshvs@msn.com
using System;
class Base
{
public virtual void Method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Method(); // Displays 'Base Method'
}
}
Or even it is possible to override a virtual method non-polymorphically inside a Derived class as shown below.
// Inheritance : Virtual methods
// Author: rajeshvs@msn.com
using System;
class Base
{
public virtual void Method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public virtual void Method()
{
Console.WriteLine("Derived method");
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Method(); // Displays 'Derived Method'
}
}
Even it is possible to omit the keyword virtual from the Derived class method or it is possible to declare the Derived class method as new.
When we want to override a virtual method polymorphically inside a Derived class, we have to use the keyword override along with the method declaration. The example is shown below.
In C#, a Base class reference can hold an object of the Derived class and when it invokes the methods, it will invoke always the Derived class methods, if you already override that method inside the Derived class by using the override keyword. Also the Base class method must declare using the keyword virtual. This is what is known as Polymorphism in C#.
// Inheritance : Virtual methods/Polymorphism
// Author: rajeshvs@msn.com
using System;
class Base
{
public virtual void Method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void Method()
{
Console.WriteLine("Derived method");
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.Method(); // Displays 'Base Method'
}
}
As with a virtual method, we must include a method body with an override method; other wise the compiler will generate an error during compilation.
Remember that in C#, we can use the override keyword with only virtual method, when overriding inside a Derived class. An overridden declaration must be identical in every way to the virtual method, it overrides. They must have the same access level; the same return type, the same name and same method signature.
The overridden methods are implicitly virtual in nature and hence they can override in subsequent Derived classes. As like virtual methods, override methods can’t be declared as static or private.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More C# Articles
More By Rajesh V S
developerWorks - FREE Tools! |
Effective governance for lean development isn’t about command and control. Instead, the focus is on enabling the right behaviors and practices through collaborative and supportive techniques. Hear from Scott Ambler on how it is far more effective to motivate people to do the right thing than it is to force them to do so. Learn how to form a lightweight, collaboration-based framework that reflects the realities of modern IT organizations. FREE! Go There Now!
|
|
|
|
Poor Requirements Management capabilities in an Enterprise have been linked to excessive project failures, escalating IT costs, and failure to deliver competitive advantage into the marketplace. Join Brianna M Smith from IBM Rational and learn about how successful organizations align IT and Business stakeholders through collaborative processes and tools for effective requirements management, and how an integrated approach across the IT lifecycle can provide unparalleled visibility and traceability to ensure that project teams are delivering on the business vision by "doing the right things" and "doing things right." FREE! Go There Now!
|
|
|
|
Learn how you can extend modern application lifecycle management to IBM System z through the IBM Rational Software Delivery Platform (SDP). The Did you say mainframe? e-kit includes podcasts, webcasts, tutorials, white and red papers, demos, and articles designed to help ease the challenges of modernizing your enterprise. This complimentary kit for mainframe developers is a practical, how-to guide for making the most of an existing development environment, including the skills and infrastructure already in place at an established enterprise. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial version of WebSphere Business Modeler Advanced V6.1.1, IBM’s premier business process modeling and analysis tool for business users that offers process modeling, simulation, and analysis capabilities. IBM WebSphere Business Modeler helps you visualize, understand, and document business processes for continuous improvement. FREE! Go There Now!
|
|
|
|
Download a free trial version of IBM Rational Developer for System z, software that can help you deliver core development capabilities; the power of Java Platform, Enterprise Edition (Java EE); and rapid application development support to diverse enterprise application development teams. With comprehensive development tools to help create, deploy and maintain traditional enterprise and composite applications, Rational Developer for System z enables developers with different technical backgrounds to easily participate in important technology projects. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial version of IBM Rational Business Developer V7.1. Rational Business Developer offers rapid and simplified development of business applications and services through Enterprise Generation Language (EGL) tools, generating Java or mainframe solutions while shielding developers from technical complexities. FREE! Go There Now!
|
|
|
|
This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product. FREE! Go There Now!
|
|
|
|
Listen to this webcast to get an overview of Info 2.0 and a technical demo of how to quickly build an enterprise mashup. IBM's Info 2.0 technology leverages emerging Web 2.0 technologies such as mashups, feeds, AJAX, and JSON in order to simplify assembly of information using feeds and services. Come learn about the technical elements of Info 2.0 including the Feed Generation framework, Mashup Engine, and mashup assembly components. Learn how to pull information from databases, departmental information, and the Web to create mashups critical to your company’s success. We will also discuss best practices to help you get started. FREE! Go There Now!
|
|
|
|
Informix Dynamic Server (IDS) Express Edition offers outstanding online transaction processing (OLTP) database performance, while helping to simplify and automate many of the tasks associated with deploying databases for small business applications. IDS 11 further extends the ease of management and applications integration with the Admin API and Scheduler, high availability with Continuous Log Restore for backup server recovery in case of a primary server failure, and column level encryption to protect personal and company private data. FREE! Go There Now!
|
|
|
|
Get a free trial download of the latest version of IBM Rational Method Composer V7.2 which helps you deliver customized yet consistent process guidance to your project teams and IT organization, and includes the latest version of IBM Rational Unified Process (RUP), which has provided process guidance to teams since 1996. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |