.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Overriding Methods in Derived Classes

Posted By:Shashi Ray       Posted Date: February 27, 2009    Points: 25    Category: C#    URL: http://www.dotnetspark.com  

Overriding Methods in Derived Classes:


Suppose we want to derive a new class called DoubleRect from Rectangle, which draws a rectangle in two colors offset by a few pixels. We must declare the base class draw method as virtual:

public virtual void draw(Graphics g) {

g.DrawRectangle (rpen, x, y, w, h);



In the derived DoubleRect constructor, we will create a red pen in the constructor for doing the additional drawing:


public class DoubleRect:Rectangle {

private Pen rdPen;

public DoubleRect(int x, int y, int w, int h):

base(x,y,w,h) {

rdPen = new Pen (Color.Red, 2);



This means that our new class DoubleRect will have to have its own draw method. However, this draw method will use the parent class's draw method but add more drawing of its own.


public override void draw(Graphics g) {

base.draw (g); //draw one rectangle using parent class

g.DrawRectangle (rdPen, x +5, y+5, w, h);



Note that we want to use the coordinates and size of the rectangle that was specified in the constructor. We could keep our own copy of these parameters in the DoubleRect class, or we could change the protection mode of these variables in the base Rectangle class to protected from private.


protected int x, y, w, h;



Shashi Ray

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend