简体   繁体   中英

How to inherit parent constants and access them?

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:

  • I would follow the .NET naming conventions , ditching the T prefix
  • I 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.

  • Consider making the types immutable instead. We can't tell whether that's feasible without knowing how you're using them, but it's at least worth considering.
  • Consider changing your inheritance model - currently you're saying that it's okay to treat a cylinder as if it's a circle, and I'd expect very few things to really work as well with a 3D solid when they're expecting a 2D shape.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM