Hi i'm new in C# console application and i'm using abstract and override but i get stack in the first method in public abstract double Compute() i got an error and it says cannot declare a body because it is marked abstract please help me. thank you!
`
abstract class Cake
{
public string _flavor, _size;
public int _quantity;
public Cake(string flavor, string size, int quantity)
{
_flavor = flavor;
_size = size;
_quantity = quantity;
}
public abstract double Compute()
{
double price;
if(_flavor == "Chocolate" && _size == "Regular")
{
price = 250.50;
}
else if (_flavor == "Chocolate" && _size == "Large")
{
price = 450.50;
}
else if (_flavor == "Strawberry" && _size == "Regular")
{
price = 300.50;
}
else
{
price = 500.75;
}
return price;
}
}
class BirthdayCake:Cake
{
public int _numOfCandles;
public BirthdayCake(string flavor, string size, int quantity, int numOfCandles):base(flavor,size,quantity)
{
_numOfCandles = numOfCandles;
}
public override double Compute()
{
return _numOfCandles * 10.00;
}
}`
Abstract methods cannot have body. Abstract class can have static fields and static method, like other classes. An abstract class cannot be declared as final.
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).
The answer lies in the error. The Main() method doesn't have a body. A method must have a body unless you have declared this inside an interface or it is marked abstract, extern, or partial. Try replacing. C#
Abstract methods don't have any implementation and require non-abstract derived classes to implement them. Of course they are allowed only in abstract classes. Override allows a method to override a virtual or abstract method from its base class.
Use virtual instead of abstract when you have a default implementation but would like to allow sub-classes to override
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With