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! |
Hear how IBM Rational Project and Portfolio Management integrated solutions help teams put the right tools and processes in place to maximize the effectiveness and efficiency of project teams and ensure that the business vision is being executed correctly. Learn how to automate and integrate requirements prioritization, top-down project planning, communications and controls, and methodology deployment to keep your scope, costs, and schedules under control. Tackle with an end-to-end approach the management of scope and scope changes, usage of methodology to control and empower project teams, and optimization of resources to align activity costs with the overall project plan. FREE! Go There Now!
|
|
|
|
Achieving true agility is a never-ending effort. We will showcase how you can become agile incrementally, a few practices at the time.Which practices should any agile team strive to adopt? What additional practices should you consider based on your needs to scale? Adopting practices are however made much easier with the right tool support. What about if your tools adapt to your practices? We will take a look at how the Jazz technology can be leveraged to make your process change the behavior of your tools. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial version of Lotus Quickr 8.0, which enables collaboration by transforming the way everyday business content such as documents, rich media, photos, and video can be shared. Lotus Quickr makes it faster and easier to share content of all types (not just documents) within virtual teams. It is designed to make it easier to collaborate across organizational boundaries, while continuing to work within the context of familiar desktop applications. FREE! Go There Now!
|
|
|
|
Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms. FREE! Go There Now!
|
|
|
|
Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered! FREE! Go There Now!
|
|
|
|
As organizations have grown increasingly dependent on online software, the risk of malicious attacks has also become far more serious. Fortunately, well-governed organizations can protect their Web applications by injecting vulnerability assessments and ethical hacks into their software development and delivery processes. This paper describes 12 of the most common hacker attacks and provides basic rules that you can follow to help create more hack-resistant Web applications. 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 Performance Tester V7.0.1, a load and performance testing solution for teams concerned about the scalability of their Web-based applications. Combining multiple ease-of-use features with granular detail, Rational Performance Tester simplifies the test-creation, load-generation and data-collection processes that help teams ensure the ability of their applications to accommodate required user loads. FREE! Go There Now!
|
|
|
|
The unprecedented scope of a service-oriented architecture (SOA) initiative brings to the forefront a number of management and governance issues that were sidestepped in the past. The key to a successful SOA implementation is managing and governing activities throughout the entire SOA delivery lifecycle by ensuring that services conform to the needs of all of the business’s stakeholders. Learn how service lifecycle management allows the business to ensure that the process by which services are defined, created, tested, deployed, optimized and retired is manageable, repeatable and auditable. FREE! Go There Now!
|
|
|
|
With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |