I have base abstract Goods
class and inherited Book
class.
abstract class Goods
{
public decimal weight;
string Title, BarCode;
double Price;
public Goods(string title, string barCode, double price)
{
Title = title;
BarCode = barCode;
Price = price;
}
}
abstract class Book : Goods
{
protected int NumPages;
public Book(string title, string barCode, double price, int numPages)
: base(title, barCode, price)
{
NumPages = numPages;
weight = 1;
}
public override void display()
{
base.display();
Console.WriteLine("Page Numbers:{0}", NumPages);
}
}
Should I write title
, barCode
, price
that exist in the Goods
class twice? Can I replace this
public Book(string title, string barCode, double price, int numPages)
: base(title, barCode, price)
with less redundant construction?
Class MembersAn abstract class may have static fields and static methods. You can use these static members with a class reference (for example, AbstractClass. staticMethod() ) as you would with any other class.
C# Abstract Class FeaturesAn Abstract class can have constants and fields.
Second, setter injection is possible in an abstract class, but it's risky if we don't use the final keyword for the setter method. The application may not be stable if a subclass overrides the setter method.
Inheritance is another feature of object-oriented programming where a particular class can derive from a base class. Multiple inheritance allows the extension of more than one base class in a derived class. Abstract classes do not support multiple inheritance.
No, this code is not redundant. You must pass values to both Book
constructor and base
constructor.
I see you assign weight
in Book
constructor. If you want, you can do the same for other Title
, BarCode
and Price
as well. Then your Goods
constructor would be empty. But That would mean that each implementation of Goods
would have to do it (which would be a bad thing if there is more logic then simple assign)..
Should I write title, barCode, price that exist in the Goods class twice? Can I replace this ... with less redundant construction?
There is no "redundancy" in this code.
This is the declaration of your constructor [method], specifying the arguments that it takes.
public Book(string title, string barCode, double price, int numPages)
This is the invocation of the base class' constructor, passing the arguments passed to this constructor.
: base(title, barCode, price)
This is absolutely necessary because your base class can only be constructed using the constructor provided that takes three arguments. You have to provide these argument, either from arguments passed to this constructor or, possibly, by deriving them, as in
: base(title, barCode, priceDerivedFrom( title, barCode ) )
(Not sure how such a function function would work but, hopefully, you see my point).
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