Can abstract classes have implementation in c#? - c#

The compiler doesn't seem to mind it so far but I just wanted to double check whether I'm setting myself up for failure in any way by implementing certain methods in my abstract class.

An abstract class usually has one or more abstract method. So yes it can have some method implemented. The goal is to force the user to implement these methods to have an object working. Sometimes abstract classes are used to provide a 'base' implementation of some interfaces, leaving the final user to specify just the key methods. You can also have an abstract class without any abstract method: in this case you are asserting you must derive from that class in order to use it.

It's common to have some implementation in abstract classes.
If there is no implementation at all, consider using an interface instead of an abstract class.

Perfectly fine to implement some methods and leave others abstract.
If all methods had to be abstract, you might as well use an interface for it.

Yes. abstract class cannot be instantiated (you have to instantiate a class that inherits from your abstract class), but it can contains implementations.

it's fine and allowed, an abstract class has at least a member (method/property) not implemented so it cannot be instantiated.
an interface is also called pure abstract class which means it's 100% abstract, so does not allow you to specify any implementation.
keep in mind that there are lots of articles and opinions about never deriving a concrete class from another concrete class but only from abstract ones... at least this was the trend in C++ up to some years ago, then I moved to the C# side, started working more and had no time to keep reading those nice articles... :)

Related

Abstract methods and hiding methods

I'm trying to understand abstract classes in c# better.
I know that in abstract classes you MUST override abstract methods and MAY override virtual methods..
my question is:
can I override non virtual methods? (I know that normally I can't - but maybe with abstract classes it's different?) or will it be like hiding ?
also, as I read here How to force call a C# derived method (the first answer) - it seems to me that because non virtual methods statically linked at compile time and can't be changed - I would not be able to call the methods in the derived class ,never? if so - what is the point of hiding a method?
I'm trying to understand abstract classes in c# better.
OK, then lets correct your mistakes, because you have some completely wrong ideas about abstract classes here.
I know that in abstract classes you MUST override abstract methods and MAY override virtual methods.
Absolutely not; the first part of that sentence is completely wrong. There is no requirement whatsoever in an abstract class to override an abstract method.
A non-abstract class is called a concrete class. The real rules are:
A concrete class must override all abstract methods of all its abstract base classes with concrete methods; it can do so either itself, or via one or more of its base classes.
This should make sense: you can't make an instance of a concrete class until every abstract method is implemented; otherwise you could invoke a method that has no implementation, and that would be bad.
Any derived class may override a non-sealed virtual method of any of its base classes.
can I override non virtual methods?
No. You can overload non-virtual methods and you can hide existing non-virtual methods, but you cannot override them.
it seems to me that because non virtual methods statically linked at compile time and can't be changed - I would not be able to call the methods in the derived class ,never?
Of course not. You call the methods of the derived class by converting the receiver to the derived class.
what is the point of hiding a method?
Duplicate of:
Is method hiding ever a good idea
Here's a BONUS QUESTION that you did not ask. See if you can answer it.
Can a method be marked as both abstract and override? If no, why not? If yes, give an example and explain why you would want to.
If you can answer that question correctly then you probably have a good understanding of abstract methods. The solution is here.
No, you can't. They must have virtual keyword. Good example here,similarThis one as well
I would advise taking a closer look into what you can do with OOP
In reference to your question, you can only override a virtual class, another of example instead of hiding methods would be:
However you can use inheritance, to use the controls from your base class. This should be done when both classes are related, to prevent creating duplicate code.
An example of this would be an individual person : Human, okay so here we use ('type of' :) stating that a person is a type of human. This is the basic use of inheritance.
This shouldn't be done if they are not related, this may seem quicker when you are doing it, however when you look back at your application 3months on you will say "Why did I do that?".
An example of this would be, this base class has a method close to what I am looking for, you need to make a comparison, is it Really? Should I actually do this?
The msdn article provided will give you the information you need to progress with this. Enjoy OOP
You have a little misunderstanding:
in abstract classes you MUST override abstract methods and MAY override virtual methods.
That sentence should really be:
in concrete classes that derive from an abstract class, you MUST override abstract methods and MAY override virtual methods, either in that class itself, one of its parent classes, or one of its subclasses.
You can use the new keyword to shadow, or hide, non-virtual methods, so yes it will be hiding and not overriding.
If you hide a method in a subclass, and then want to call the method as it appeared in the base class, cast the subclass as the to the base class type, as done in the second example here.

What is different between an abstract and an Interface class in C#?

What is different between an abstract and an Interface class in C#?
An interface is not a class, it is just a contract that defines the public members that a class must implement.
An abstract class is just a class from which you cannot create an instance. Normally you would use it to define a base class that defines some virtual methods for derived classes to implement.
Rather than writing whole thing here..
try http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
A class can implement multiple interfaces but can only inherit from one abstract class.
An abstract class can provide implementation for it's methods. An interface cannot provide implementations.
the level of interface is higher than abstract.
when u're design the strcuture, draw the uml, u should use interface.
when u're implement, then u should use abstract to extract repeat things.
anyway, the different is not only a syntax problem..
hope it helps.
Google "abstract class vs interface" and you'll get lots of explanatory articles...
A class can implement multiple
interfaces but can only inherit from
one abstract class.
Also, abstract classes may have some functions defined but interfaces will not have any function definition and the deriving class must define all of them.
I would explain this through the usage. Abstract class can be used when there is only one hierarchy, additionally without default implementation; while interface can be used across hierarchies (horizontally), often referred to as a behavior.
Interface is also an abstraction and in c# substitutes multiple class inheritance, so this may be confusing, but you have to distinguish when to use what.
Hope this helps,
Robert
The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

Should a base class be marked abstract if there are no abstract members?

Is it okay for a class to be marked as abstract if it has no abstract members? Even if there is no practical reason for to directly instantiate it? (aside from unit tests)
Yes, it is reasonable and beneficial to mark explicitly as abstract a base class that should not be instantiated -- even in the absence of abstract methods.
It enforces the common guideline to make non-leaf classes abstract.
It prevents other programmers from creating instances of the class. This may make it easier for you to add abstract methods to it later.
Do you want that class to ever have an actual instance? If yes, then don't mark it abstract. If no, then mark it abstract.
Short answer: yes.
Long answer: The abstract keyword marks a class and/or its members as not being useful directly. Why this may be varies from case to case; an abstract class may be too basic to do any real work, or it may have abstract members that are required to exist for other code in this class to work, but cannot be concretely defined at this level. The short of it is that by marking a class abstract, you tell the compiler and other developers not to instantiate this class directly, but instead to inherit from it to create a concrete useful implementation. You can do this even if the class has a working implementation for all its members, if you feel that the class must be inherited to make the best use of that implementation.
If the goal is to make a base class that other classes will extend, it makes sense to make this an abstract class.
If, however, the goal is to make some form of Utility class -- one that has only static members -- the best way to handle this is to give the class a single constructor marked private. That way, the class can not be instantiated, nor subclassed. This sends a clear signal that the only use of the class is to use its static methods. (This is a tip from Effective Java, by Josh Bloch)
Yes, I think so. At least that's what I do from time to time ;-)

What do you use if you want to ensure that all methods and properties are implemented

I was giving a test and got one question.
QUESTION:
What do you use if you want to ensure that all methods and properties are implemented?
a)Inheritance.
b)Polymorphism.
c)Encapsulation
d)Interface.
I think its Interface. Am I right or the. ans is diff?
Yep, use an interface. An interface is basically a contract saying "hey, you need to implement these members, or I'm not going to compile."
An interface or an abstract class will accomplish what you want. In an abstract class, if a method is marked as abstract, then it must be implemented in the derived class. The question really comes down to which one you should use. An interface, or an abstract class.
The quick answer (and I do mean quick and dirty) is that you should use an interface when you are trying to set up contractual behavior between classes. You should use an abstract class when the set of derived class have some shared behavior.
An interface will ensure that the class has method stubs for all the methods, but they may not be implemented and may throw NotImplementedExceptions.
A better way to ensure that all methods are implemented would be using unit tests where you check that the methods actually do what they should.
Actually, these concepts don't even compare to each other.

Abstract classes vs Interfaces

I'm a bit confused about the usage of Abstract classes in C#. In C++, it makes sense to define a template which classes inheriting the abstract class can follow. But, in C# doesn't Interface serve the same purpose?
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
I still like to provide a default abstract implementation of an interface, assuming it's a substantial interface (and it makes sense). You never know when you might add something to the interface that has an easy default implementation that could be included and given "for free" to anyone who inherits from the abstract base class.
This CodeProject article has a lot of information on the difference between the two including a table comparing and contrasting the features of each.
Interfaces define the contract between classes - the ways classes call each other. A class can implement multiple interfaces, but can only inherit from one abstract class.
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
Yes :). If it makes sense to implement some methods in the base class which will be common to all inhereted class you should use an abstract class. If the base class would only be used to define an interface but there is no common logic between the inherited classes, use an interface.
Interfaces and abstract classes serve different goals. Interfaces are used to declare contracts for classes while abstract classes are used to share a common implementation.
If you only use abstract classes, your classes cannot inherit from other classes because C# does not support multiple inheritance. If you only use interfaces, your classes cannot share common code.
public interface IFoo
{
void Bar();
}
public abstract class FooBase : IFoo
{
public abstract void Bar()
{
// Do some stuff usually required for IFoo.
}
}
Now we can use the interface and base implementation in various situations.
public class FooOne : FooBase
{
public override void Bar()
{
base.Bar(); // Use base implementation.
// Do specialized stuff.
}
}
public class FooTwo : FooBase
{
public override void Bar()
{
// Do other specialized stuff.
base.Bar(); // Use base implementation.
// Do more specialized stuff.
}
}
// This class cannot use the base implementation from FooBase because
// of inheriting from OtherClass but it can still implement IFoo.
public class FooThree : OtherClass, IFoo
{
public virtual void Bar()
{
// Do stuff.
}
}
For your first question, Yes.
For your second answer i'll give you some tips I've followed.
Use abstract classes and interfaces in combination to optimize your design trade-offs.
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning.
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.
Use an interface
When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
Use an interface to design a polymorphic hierarchy for value types.
Use an interface when an immutable contract is really intended.
A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.
You can implement any number of Interfaces, but can only inherit one Class. So Classes and Interfaces are quite different beasts in C# and you cannot use them interchangeably. In C# abstract classes are still classes, not interfaces.
If you don't have any default/common code, then go with an interface.
An abstract class can also serve as a template, where it defines the steps of some algorithm and the order in which they are called, and derived classes provide the implementation of these steps:
public abstract class Processor
{
// this is the only public method
// implements the order of the separate steps
public void Process()
{
Step1();
Step2();
//...
}
// implementation is provided by derived classes
protected abstract void Step1();
protected abstract void Step2();
}
Whilst it's true that an abstract class with no implementation is equivalent to an interface, interfaces and abstract classes are used for different things.
Interfaces can be used for polymorphism in the most general sense. For example, ICollection is used to define the interface for all collections (there are quite a few). Here it is defining the operations that you want to perform on a certain kind of type. There are many other uses (such as testability, dependency injection etc). Also, interfaces can be mixed and this works both conceptually and technically.
Abstract classes are more to do with templateable behaviour, where virtual methods are a place to 'fill in the gaps'. Obviously you can't mix abstract classes (at least, not in C#).
In C# a large deterrent for the use of abstract classes is that you can only use one. With interfaces you have the advantage of not limiting the base class for the implementation. To this end, I always use an interface even if I create an abstract base class to aid with the implementation.
Often another annoyance of base abstract classes is that they tend to rely on template arguments. This can make it very difficult for the rest of your code to utilize. The easy answer for this is to provide an interface to talk to the abstract class without knowing the type argument of the template class.
Others seem to be typing their answer faster, but allow me to summarize...
Use an interface. If you need to share implementation, you can also create an abstract base class that provides common implementation details.
Note that with C#3, you can provide default behavior for interfaces through the use of extension methods. There are some limitations, though, and abstract classes still have their place.
The rule I follow when modeling is:
Classes(abstract included) and structs model entities.Interfaces model behavior.
Entities implementing an interface can be considered as exhibiting behaviors that the interface(contract) exposes.
This is hinted at in a few of the answers but not explicitly stated.
The fact that you can implement multiple interfaces and only inherit from one base class, as if they were two sides of the same coin, isn't a good way to look at it.
Don't think of interfaces as part of an object hierarchy. They are usually just small parts of functionality (or at least specific if not small) that your real object heirarchy can declare as implementing. Take IDisposable for instance. If you were the one writing that, would you ask yourself whether it should have been an abstract class or an interface? It seems obvious that in this case they are two completely different things. I want to BE disposable. Think ICloneable and IEnumerable. You can implement those in your class without having to try and make your class derive from some unrelated classes like List or Array. Or take IEnumerator. Simply gives a MoveNext type of view to an object. My class can provide that functionality without having to awkwardly be derived from some other sequential collection data type that has nothing to do with my class.
I always prefer interfaces as long as the base class don't have some really "heavy duty" implementation that will save lots of time to the implementers.
giving that .net allows only one base class inheritance, forcing your users to inherit is a huge limitation.
You should always prefer programming to interfaces than to concrete classes.
If you also want to have a default implementation you can still create a base class which implements your interface(s).

Categories