Abstract Classes
Abstract classes are designed to be inherited from. An abstract class can only be used as the base class of another class. Here's some restrictions regarding abstract classes:
When compile and run the code, you can see following display:
- An abstract class can not be instantiated.
-
An abstract class is declared using the
abstract
modifierabstract class [Class Name] { ... }
- An abstract class can contain abstract members or regular, nonabstract members. The members of an abstract class can be any combination of abstract members and normal members with implementations.
- An abstract class can itself be derived from another abstract class.
- Any class derived from an abstract class must implement all the abstract members of the class by using the override keyword, unless the derived class is abstract.
public abstract class shape //abstract class { protected string name; public void printName() //regular member { Console.WriteLine(name); } public abstract double getArea(); //abstract member } public class circle:shape { public double radius; private const double PHI = 3.146F; public circle(double Radius) { name = "Circle"; radius = Radius; } public override double getArea() //implementation of getArea() { return PHI * radius * radius; } } public abstract class rectangular:shape //abstract class can be inherit to abstract class { protected double width; public override abstract double getArea(); //abstract inherited class, can define inherited abstract method } public class square : rectangular { public square(double Width) { name = "square"; width = Width; } public override double getArea() //implementation of getArea() { return width * width; } } public class rectangle : rectangular { private double length; public rectangle(double Width, double Length) { name = "square"; width = Width; length = Length; } public override double getArea() //implementation of getArea() { return width * length; } } class Program { static void Main(string[] args) { circle myCircle = new circle(3.7F); myCircle.printName(); Console.WriteLine("Area = " + myCircle.getArea()); square mySquare = new square(6.7F); mySquare.printName(); Console.WriteLine("Area = " + mySquare.getArea()); rectangle myRectangle = new rectangle(4.4F, 7.54F); myRectangle.printName(); Console.WriteLine("Area = " + myRectangle.getArea()); } }
When compile and run the code, you can see following display:
Circle
Area = 43,068739856739
square
Area = 44,8899974441529
square
Area = 33,1760005512238
Area = 43,068739856739
square
Area = 44,8899974441529
square
Area = 33,1760005512238
0 comments:
Post a Comment