I have a code below that has an Interface, abstract class and a class. I want to disable the implementation of the abstract method Print() in the FreeCustomer Class. Is this possible? Thank you very much.
public interface ICustomer
{
string CustomerName { get; set; }
double Amount { get; set; }
string Print();
}
public abstract class Customer : ICustomer
{
public string CustomerName { get; set; }
public double Amount { get; set; }
public abstract string Print();
}
public class GoldCustomer : Customer
{
public override string Print() {
return "You are a Gold Customer: " + CustomerName;
}
}
public class FreeCustomer : Customer
{
}
Even if it were possible, it would be a bad idea: Why do you want to implement only part of a contract?
It seems that you are having this issue because the ICustomer interface is trying to do too many different things (and thereby violates the Interface Segregation Principle).
If you don't always need, or want to implement, the Print method, then take it out of the interface, or move it into a separate interface.
The only case when a derived class does not need to implement abstract method of base class is when you declare the derived class as abstract as well.
As MSDN doc says here,
"If a base class declares a member as abstract, that method must be overridden in any non-abstract class that directly inherits from that class. If a derived class is itself abstract, it inherits abstract members without implementing them."
So you may Declare FreeCustomer to be abstract and then need not implement print in there, although I don't see it serving any purpose.
In your particular case, do not declare the function as abstract in the base Customer class - instead use public virtual, and provide an empty implementation in the base class.
Then all you have to do is override it in the classes where you actually need the Print() functionality, in everything else it will do nothing (because the base implementation will be used). This means you can keep it on the interface.
Related
I have a following interface:
interface IName
{
string Name { get; }
}
And some base class BaseClass. Childs of this class may implement IName interface, but not all of them do.
If a Child implements IName, I would also like to override ToString() method, exactly the same way for all cases, as follows:
public override string ToString()
{
return Name;
}
It seems that a good place for overriding ToString() would be in IName interface, but i believe that it is not possible in C#.
Implementing ToString() in every class seems a bad idea too, because it's a lot of code redundancy (and a waste of time).
What is a proper solution for a case like this?
I'd suggest to make a second base class as such:
public abstract class BaseClass
{
// your base class implementation
}
public abstract class NamedBaseClass : BaseClass, IName
{
public string Name { get; set;}
public override string ToString()
{
return Name;
}
}
this way, if you want a child to implement both BaseClass and IName, then you should inherit from NamedBaseClass.
According to your words that "some might implement IName and some not", then BaseClass should not implement IName, but you should still have some sort of a base implementation. this is my solution.
EDIT:
to make a single class which returns the name and has nothing to do with BaseClass, then you can make an unrelated abstract implementation just for that:
public abstract class NameStringClass : IName
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
Consider cFoo as the child class which has IName. And cBar parent class, and cBaz as a class which doesnt implement IName.
public interface IName
{
string Name { get; }
}
public class CBaz : CBar
{
}
public class CFoo : CBar, IName
{
public CFoo(string name)
{
Name = name;
}
public string Name { get; }
}
abstract public class CBar
{
public override string ToString()
{
if (this is IName)
{
var temp = (IName) (this);
return temp.Name;
}
else
{
return base.ToString();
}
}
}
[Old Answer]
Note that an interface is essentially empty. You need to think of an interface as bearing more of the meaning of contract, implying that the person whom implements this interface as requiring to implement a property/method/field/etc of such signature.
For implementation specific tasks which may be shared commonly by many classes, an abstract class is more suitable.
The moment you need to resolve some kind of logic, you must go through a gateway of implementation, some implementation must occur, interfaces are essentially empty templates. The most loose way of implementing this is via an abstract class which contains both the name property and the ToString override, from which you then inherit from for all your subsequent classes.
At the same time you can consider an abstract class for your CBar class. As well as calling the base method base.ToString().
[End of Old Answer]
I have this interface
public interface IColumn
{
bool IsVisible {get;set;}
bool IsGroupBy { get; set; }
Type CLRType { get; set; }
string GetGroupByString();
string GetFilterString();
}
and i have classes which will inherit from it, for the first 3 properties the implementation is exactly the same.
for string GetGroupByString(); the implementation is the same for all classes except 2
so i made an abstract class called ColumnBase which inherits the IColumn interface and implements all of its members and added backing fields because i need to implement INotifyPropertyChanged.
and made my classes inherit from ColumnBase and i did override the implmentations that are not meant to be the same.
I have a very limited experience with Interfaces and Abstract classes, my question is if you had an Interface and some classes that will inherit from it and you realized that the implementation for some but not all properties and functions is the same, do you create an abstract class and put the default implementation and override it inside the classes that have special implementation?
This will get you answers based on opinion and preference.
IMHO, I think this would be best suited to an abstract class with the two methods requiring differing implementations being declared as abstract methods; using abstract on the methods means that the implementations must have an implementation of that method.
public abstract class ColumnBase
{
public bool IsVisible { get; set; }
public bool IsGroupBy { get; set; }
public Type CLRType { get; set; }
public virtual string GetGroupByString()
{
return "base string";
}
public abstract string GetFilterString();
}
public class ConcreteColumn : ColumnBase
{
public override string GetGroupByString()
{
return "concrete string";
}
public override string GetFilterString()
{
return "who owns the filter string?";
}
}
do you create an abstract class and put the default implementation and override it inside the classes that have special implementation?
Yes, I would do it exactly.Actually it's kind a purpose of abstract classes and virtual / override features.In your case I think you don't need IColumn interface,you can use an abstract class.And implement all common methods inside of it, then if you want to change behavior of a method override it in nested class.
If you mark a method with virtual you can override it in nested classes and you can change the behaviour of this method depends on your current class.You might want take a look at the documentation for more details.
If your derived class is some specialized version of the base class then it would be a good idea to inherit it from the a base class, like class Rectangle : Shape. This why the derived classes are all specialized version of a same thing. For example Rectangle and Circle are in fact, inherently a shape. But consider using interfaces when you have different objects and you want some similar behaviors. For instance, you can serialize a Bird object and a Chair object, even if they have only Name and Age properties, it's not a good idea to derive them form a base class which has a Name and Age properties and Serialize() method, because they are different things. Although the implementation of Serialize() method would be the same in both of them, it's better to have an ISerializable interface and implement it in both classes.
I have an abstract base class for a generic 'Device' type and would like to require the derived specific device classes to initialize a list based on their respective differences.
When one sets the derived class to active it must go through the list to set the parameters to active as well. Each derived class will insert their own parameters into the list.
Here is the relevant code:
Base class:
abstract public class Device : Common, IDisposable
{
abstract public Boolean bActive
{
get;
set;
}
abstract List<Parameters> ActiveParameters;
...
}
I don't wish to initialize the List in the base class because I do not know which parameters are going to be inserted into the list from the derived class. This code produces an error saying that I cannot have an abstract field and I understand that but is there a way to require a derived class to initialize a field from the base class?
This code produces an error saying that I cannot have an abstract field and I understand that but is there a way to require a derived class to initialize a field from the base class?
If this is required to be implemented, it should be part of your API. To handle this, you can make this a protected property. This will force it to be implemented by all derived classes.
protected abstract List<Parameters> ActiveParameters { get; }
If this is about initializing the list, then you can force that by putting that list into the constructor (or all constructors, if you have more of them) of the base class.
Something like:
public abstract class Device : Common, IDisposable
{
protected Device(List<Parameters> activeParameters)
{
ActiveParameters = activeParameters;
}
protected List<Parameters> ActiveParameters { get; private set; }
}
The derived class will be then forced to do something like:
public class ConcreteDevice : Device
{
public ConcreteDevice()
: base(new List<Parameters>())
{}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interface vs Abstract Class (general OO)
In one of the MSDN article following line is mentioned
Interfaces cannot specify new members in later versions while
abstract classes can add members as needed to support additional
functionality.
I picked this sentence from here. You can read the same sentence in paragraph 3.
I have a confusion, sorry in advance for in case I am missing something.
Once the Abstaract Class or Interface is declared and then any Derived class is inheriting the methods, in either case, all the methods should be overridden. Otherwise compilation error will come.
Your comments?
Once the Abstaract Class or Interface is declared and then any Derived class is inheriting the methods, in either case, all the methods should be overridden. Otherwise compilation error will come.
No, for an abstract class only the abstract methods need to be overridden. You can add non-abstract methods with no errors.
For example, version 1:
public abstract class FooBase
{
public abstract void Bar();
}
public class FooImpl : FooBase
{
public override void Bar() {}
}
Now introduce a new non-abstract method in FooBase for version 2:
public abstract class FooBase
{
public abstract void Bar();
public void NewMethod() {}
}
... and there's no problem.
Note that for company internal code, where all the code which is going to use the API is rebuilt at the same time, this is often not a problem at all, with either interfaces or abstract classes. If you want to add a method to an interface, you can do so as you can upgrade all implementations at the same time.
It's really when you don't have control over the whole code base that you need to be careful.
an class implementing an interface MUST implement all methods and properties defined in the interface.
when inheriting from an Abstract class, you MUST implement/override all the Abstract members, but any non-abstract members will be inherited just as when you inherit from a concrete class.
When you inherit from Interfaces, you must implement all members of that interface. But you can expand on the interface as you deem fit. You can also inherit multiple interfaces. Valid Example:
public interface IPerson
{
string FullName { get; set; }
string SSN { get; set; }
}
public interface IPersonDBContext
{
void Save(IPerson person);
}
public class PersonData : IPerson, IPersonDBContext
{
// Implements IPerson FullName
public string FullName { get; set; }
// Implements IPerson SSN
public string SSN { get; set; }
// Implements IPersonDBContext Save()
public void Save(IPerson person)
{
// Code to save the IPerson instance to the DB...
}
// Added method, not included in any interface...
public void Validate(IPerson person)
{
// Code to validate the IPerson instance...
}
}
Now, for Abstract classes, you can include concrete methods that can be inherited, but also specify some methods that must be overridden. However, note, you cannot have more than one Base Class (and an Abstract Class is still a class...) So you can't mix two abstract classes like you can an interface. Example:
public abstract class Person
{
public string FullName { get; set; }
public string SSN { get; set; }
public abstract void Save();
}
public class PersonData : Person
{
// Implements Abstract Person Save() Method
public override void Save()
{
// Save logic here...
}
// Non-inherited member...
public void Validate()
{
// Access properties of the base class (Abstract Person)
this.FullName.ToString();
this.SSN.ToString();
}
}
Lastly, and most powerfully, you can mix a single abstract base class with as many interfaces as you want... So, If I kept the Abstract class Person, from example 2, and the Interface IPersonDBContext from example 1, I could do this:
public class PersonData : Person, IPersonDBContext
{
// Implements Abstract Person Save() Method
public override void Validate()
{
// Access properties of the base class (Abstract Person)
this.FullName.ToString();
this.SSN.ToString();
}
// Inplmenets IPersonDBContext Save()
public void Save(Person person)
{
// Save logic here...
}
// Non-inhereted method
public void Clone(Person person)
{
// Logic to make a member-wise clone.
}
}
Hope that helps...
Implementing an interface forces you to override its methods - inheriting a class however gives you a choice. Only abstract methods needs to be overriden. The MSDN excerpt points out that the price of a strict interface contract can prove to be expensive later on, when all implementors will need to implement the added methods. Using a class parent with virtual methods let you decide later on whether you need a specialization.
I'm not really sure what looks better or when do I really use in abstract classes and properties, or when to use non abstract properties. I'll try to make a simple example. Let's say I have this:
abstract class Human
{
public GenderType Gender { get; set; }
public string Name { get; set; }
public Date Born { get; set; }
public bool IsNerd { get; set; }
abstract public void Speak();
abstract public void Sleep();
abstract public void AnoyingPeopleOnStackOverflow();
//... so on
}
class Peter : Human
{
//Peter is special, he got a second name
//But thats all, everything else is the same as like on other humans
public string SecondName { get; set; }
//...override abstract stuff
}
Is this alright? As I understood, I don't have to use an abstract property if I dont want to override it. And in this situation it would be ok, just the methods like Speak, Sleep and so on should be abstract.
Now, if this is ok, when would or should I use an abstract property?
Use an abstract property when you have no default implementation and when derived classes must implement it.
Use a virtual property when you have an implementation in the base class but want to allow overriding.
Use the override keyword to override a member. Mark the member as sealed override if it should not be overridden again.
Don't mark the property as abstract or virtual if you don't want it to be overridden.
Use the new keyword to hide a non-abstract, non-virtual member (this is rarely a good idea).
How to: Define Abstract Properties
I find that abstract properties often occur in a design which implies that they will have type-specific logic and/or side effects. You are basically saying, "here is a data point that all subclasses must have, but I don't know how to implement it". However, properties which contain a large amount of logic and/or cause side effects may not be desirable. This is an important consideration, though there is no fixed right/wrong way to do it.
See:
Should Properties have Side Effects
CA1024: Use properties where appropriate
Personally, I find that I use abstract methods frequently but abstract properties rarely.
I know what I want them to do, I don't care how they do it: Interface.
I know what I want them to do, I don't care how they do some of it, but I've firm ideas on how they'll (or at least most of them) do other bits: Abstract class.
I know what I want them to do, and how most of them will do it: Concrete class with virtual members.
You can have other cases such as e.g. an abstract class with no abstract members (you can't have an instance of one, but what functionality it offers, it offers completely), but they're rarer and normally come about because a particular hierarchy offers itself cleanly and blatantly to a given problem.
(Incidentally, I wouldn't think of a Peter as a type of Human, but of each peter as an instance of human who happens to be called Peter. It's not really fair to pick on example code in this way, but when you're thinking about this sort of issue it's more pertinent than usual).
Abstract members are simply virtual members that you have to override. You use this for something that has to be implemented, but can't be implemented in the base class.
If you want to make a virtual property, and want that it has to be overridden in the class that inherits your class, then you would make it an abstract property.
If you for example have an animal class, its ability to breathe would not be possible to detemine just from the information that it's an animal, but it's something that is pretty crucial:
public abstract class Animal {
public abstract bool CanBreathe { get; }
}
For a fish and a dog the implementation would be different:
public class Dog : Animal {
public override bool CanBreathe { get { return !IsUnderWater; } }
}
public class Fish : Animal {
public override bool CanBreathe { get { return IsUnderWater; } }
}
Use abstract when all sub-classes have to implement the method/property. If there's no need for each and every sub-class to implement it, then don't use it.
As for your example, if SecondName is not required for each person, then there's no need to make an abstract property in the base class. If on the other hand, every person does need a second name, then make it an abstract property.
Example of correct usage of an abstract property:
public class Car
{
public abstract string Manufacturer { get; }
}
public class Odyssey : Car
{
public override string Manufacturer
{
get
{
return "Honda";
}
}
}
public class Camry : Car
{
public override string Manufacturer
{
get
{
return "Toyota";
}
}
}
Making Maker abstract is correct because every car has a manufacturer and needs to be able to tell the user who that maker is.
An abstract property would be used where you want the class to always expose the property, but where you can't pin down the implemetation of that property - leaving it up to/forcing the inheriting class to do so.
There's an example here, where the abstract class is named Shape, and it exposes an abstract Area property. You can't implement the Area property in the base class, as the formula for area will change for each type of shape. All shapes have an area (of some sort), so all shapes should expose the property.
Your implementation itself looks just fine. Was trying to think of a sensible example of an abstract property for a Human, but couldn't think of anything reasonable.