In this example, two classes, Cube and Square, implement an abstract class, Shape, and override its abstract Area property. Note the use of the override modifier on the properties. The program accepts the side as an input and calculates the areas for the square and cube. It also accepts the area as an input and calculates the corresponding side for the square and cube.
// overridding_properties.cs
// Overriding properties
using System;
abstract class Shape
{
public abstract double Area
{
get;
set;
}
}
class Square: Shape
{
public double side;
// Constructor:
public Square(double s)
{
side = s;
}
// The Area property
public override double Area
{
get
{
return side*side ;
}
set
{
// Given the area, compute the side
side = Math.Sqrt(value);
}
}
}
class Cube: Shape
{
public double side;
// Constructor:
public Cube(double s)
{
side = s;
}
// The Area property
public override double Area
{
get
{
return 6*side*side;
}
set
{
// Given the area, compute the side
side = Math.Sqrt(value/6);
}
}
}
public class MainClass
{
public static void Main()
{
// Input the side:
Console.Write("Enter the side: ");
string sideString = Console.ReadLine();
double side = double.Parse(sideString);
// Compute areas:
Square s = new Square(side);
Cube c = new Cube(side);
// Display results:
Console.WriteLine("Area of a square = {0:F2}",s.Area);
Console.WriteLine("Area of a cube = {0:F2}", c.Area);
// Input the area:
Console.Write("Enter the area: ");
string areaString = Console.ReadLine();
double area = double.Parse(areaString);
// Compute sides:
s.Area = area;
c.Area = area;
// Display results:
Console.WriteLine("Side of a square = {0:F2}", s.side);
Console.WriteLine("Side of a cube = {0:F2}", c.side);
}
}
No comments:
Post a Comment