Virtual method has an implementation & provide the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.
important Notes:
(a)Any Class with abstract method or property in it must be declared abstract
(b)Attempting to instantiate an object of an abstract class retults in a compilation error
Example:
|
Shape m_MyShape = new Shape(); //it is Wrong to that. |
But we can do that.
|
Shape m_MyShape = new Circle(); // True |
Or
|
Shape m_MyShape;
/*
declare refrences only, and the refrences can refer to intances of
any concrete classes derived from abstract class
*/
Circle m_MyCircle = new Circle();
m_MyShape = m_MyCircle; // Also True |
(d)An abstract class can have instance data and non-abstract methods -including constructors-.
Tutorial
Our Tutorial has 4 classes { Shape --> Point --> Cirlce --> Cylinder } Abstract Class Shape has 2 virtual methods Area() & Volume(), and one abstract property ShapeName
Class Point only override the inherited property ShapeName as point do not have any area or volume Also it has to properties X & Y (pntA[X,Y]) for example
Class Cirlce override method Area() & the property ShapeName and doen't override volume as it has no volume. Also Cirlce has some methods to provide its Diameter & Circumference which will be used by class Cylinder.
Class Cylinder override all methods in Class Shape, and use the service methods in Class Circle (Diameter & Circumference) to calculate the Area() & Volume(). Check the roject and it is well commented.