How to access the const variable from the parent class?
I have a PI constant and I want to use it in the TCylinder class, how can I access it? I know that I can use Math.PI, but for the future I want to know
class TCircle {
const double PI = 3.14;
private double radius;
public double Radius { get => radius; set => radius = value; }
public TCircle(double radius)
{
this.radius = radius;
}
public virtual double GetArea()
{
return PI * this.radius * this.radius;
}
class TCylinder : TCircle {
private double height;
public TCylinder(double radius, double height)
: base(radius)
{
this.height = height;
}
public override double GetArea()
{
return (2 * base.GetArea()) + (2 * PI * height);//want to access PI
}
}
You have not specified an access modifier for that property, so it will default to private
. Use protected
instead and classes that inherit it, can see it.
As Moo-Juice has said, if you give the constant an access modifier other than private
, it'll be fine.
However, I'd recommend something slightly different: get rid of the constant altogether. It already exists (in a rather more precise form) in System.Math
. You can use it without any qualification if you add:
using static System.Math;
at the top of each source file.
As other suggestions:
T
prefixI would use an automatically implemented property instead of a manually implemented property with a separate field:
public double Radius { get; set; }
Then just use the property everywhere.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.