Folks
I am surprised to see my code working, that I dont have any abstract method in abstract class. But as per rules we should have atleast one abstract method right ? :S
No, you don't need an abstract method in an abstract class.
The restrictions are:
If a class has an abstract method, property, index, or event then the class must also be abstract.
You can't instantiate an abstract class.
There is no requirement that abstract classes must have abstract methods.
No, this is entirely valid. Indeed, every static class in C# is actually an abstract and sealed class in .NET. (You can't declare an abstract class to be sealed with C# source code though.)
The C# 4 spec explicitly calls this out, in section 10.1.1.1 (abstract classes):
An abstract class is permitted (but not required) to contain abstract members.
It's certainly rare to have an abstract class with no abstract members, but it's not unheard of. (Don't forget that it's not just methods that can be abstract - you can have abstract events and properties, too.)
From MSDN - abstract (Emphasis added):
An abstract class may contain abstract methods and accessors.
Your abstract class can contain nothing but non-abstract methods, or it could be am empty class if you want. It gives you a base class that cannot be instantiated, which could be useful for plymorphism.
You don't need abstract methods to have an abstract class. Sometimes it's useful to just restrict a class from being instantiated, and designate it as a base to some inheritance hierarchy. All the methods can be defined in an abstract class.
Related
http://msdn.microsoft.com/en-us/library/ms182126.aspx
Microsoft Design Guidelines say that Abstract Types should not have a Constructor.
To me, it seems very plausible that most classes that derive from an abstract class will have a constructor very similar to, if not identical to, its base.
If for no other reason but to follow DRY, is it really terrible to have abstract classes with Constructors if it means that all your derived classes now only need to put
public DerivedClass()
: base()
{
}
Or is there something that I am missing?
There's nothing to prevent you from doing that but by definition abstract classes are those that cannot be instantiated. So if you create a constructor, make it protected, not public otherwise your class won't meet the definition of abstract.
The guideline you mentioned further explains:
Cause: A public type is abstract and has a public constructor.
and
Rule description: Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.
How to Fix Violations: To fix a violation of this rule, either make the constructor protected or do not declare the type as abstract.
I need to inherit from a basic abstract class. I want to override only one method. But Visual Studio oblige me to override them all, So I am overriding more than 10 methods that throw NonImplementedException, I find it stupid. Isn't there any way to override only what I need. Or at least to tell Visual Studio to override the rest (non implemented methods and properties)?
The base class is written by the framework so I can't change it (I am talking about RoleProvider of ASP.NET MVC)
abstract class Base
{
public void Method1()
{
//some code
} // No need to override
public abstract void Method2(); // must be overriden
public virtual void Method3()
{
// some code
} // Not necessarily be overriden
}
class Derived : Base
{
}
Here the compiler will only ask you to override Method2() as a mandate. It won't ask you to override Method1() or Method3(). You can override Method3() as it bears keyword virtual though.
If the method is abstract , you must override.
If the method is virtual , you can override but not necessarily
The real problem here is that you have a base class with so many methods that a derived class can work only with a subset of them. This means that your base class most likely has multiple responsibilities and thus violates the Single Responsibility Principle (SRP).
The solution is to split your base class into several smaller classes where each of them has exactly one responsibility.
If the base class is not from you, you really need to implement all of those methods.
If the base class is a class that violates the SRP and your implementation can really work correctly if you implement only a small subset of the methods you could create an abstract base class deriving from that other abstract base class. In your abstract base class you can implement all methods you don't need and throw a NotImplementedException. Don't implement those methods you need.
Now, derive a class from your base class - you now only have to implement the methods you are interested in. Be sure to document this properly.
Isn't there any way to override only what i need.
No, that's how abstract classes work. If you make your class abstract as well you don't need to implement all methods.
It is necessary to override all the methods which are declared as abstract. you cannot skip the non-concrete methods. If you really want to do then make your class as abstract. you cannot change the mechanism of abstraction.
Remember, abstract classes have the following features:
An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessors.
It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
You could also create an abstract class which would inherit and implement all methods (with NotImplementedException), and then your subclasses could inherit that abstract class and implement only the methods that are relevant for you.
I have the following code:
public class HitController : MonoBehaviour, ICentroidHitListener
The way I understand it. HitController inherits from MonoBehaviour and implements the methods in the ICentroidHitListener.
But how can I code this if I just want it only to implement the methods in the ICentroidListener? Do I code it like this:
public class HitController : ICentroidHitListener
In which case that looks like HitController inherits from ICentroidHitListener
If it's an interface, : implements the interface. If it's a class, : inherits from the class.
Therefore HitController : ICentroidHitListener is correct.
Generally, there is no way to differentiate an interface from a class using the : syntax.
That's why it's important to add an I prefix to all your interfaces.
The code you provided, public class HitController : ICentroidHitListener, is correct, and the readers of your code should be able to easily and quickly deduce that it is an interface based on the I prefix.
Taken from here:
When a class or struct implements an interface, the class or struct
provides an implementation for all of the members defined by the
interface. The interface itself provides no functionality that a class
or struct can inherit in the way that base class functionality can be
inherited. However, if a base class implements an interface, the
derived class inherits that implementation. The derived class is said
to implement the interface implicitly.
Taken from here:
Inheritance enables you to create new classes that reuse, extend, and
modify the behavior that is defined in other classes. The class whose
members are inherited is called the base class, and the class that
inherits those members is called the derived class. A derived class
can have only one direct base class. However, inheritance is
transitive. If ClassC is derived from ClassB, and ClassB is derived
from ClassA, ClassC inherits the members declared in ClassB and
ClassA.
In C#, as opposed to languages like C++, multiple inheritance is not allowed, meaning that a class cannot inherit from more than one other class. Conversely, a class can implement more than one interface.
"inheritance" implies extending existing behaviour. An interface has no behaviour, you have to implement all the behaviour of the methods/properties defined in the interface. Hence you "implement" an interface and cannot really inherit anything from it.
If you inherit from something else, you inherit all its concrete behaviour. If some other class implements an interface you don't have to also implement that interface. Now, the class that "implements" that interface could make one or more of those interface implementations "abstract"; in which case you'd be forced to implement the abstract members of the class you're deriving from. But, you don't have to implement that interface--you inherit the interface from the base. You can include the interface in the "base class list" for the derived type, but it's not necessary.
By that token, you'd also "implement" an entirely abstract class. But, it's rare that anyone would use that terminology. For the most part "interface" is syntax sugar in .NET; but it does have IL-level support. e.g. an entirely abstract base class is semantically identical to an interface.
Interfaces let you ensure the only thing you can do is define an interface and not behaviour (an abstract class can have behaviour).
The answer to what you're asking is "yes", if I understand it correctly.
In the first example, you are inheriting from a base class (MonoBehavior) and implementing an interface (ICentroidHitLIstener').
You have access to all the members of MonoBehavior from your HitController class, and your HitController class must provide implementation for all members defined in the ICentroidHitListener interface.
In the second example, you are only implementing the ICentroidHitListener interface.
That's easy.
Inheriting is gaining base class features to yours.
Implementing is creating features according to specified protocol.
class:class and interface:interface is inheritance,
class:interface is implementing,
class:abstract_class are both implementing and inheritance.
I'm not familiar on using abstract class.
I'm trying to call a abstract class and get this error Cannot create an instance of the abstract class or interface and I already research this error but I'm really confused on this.
Here's my code:
string B1String;
while ((B1String = OasisFile.ReadLine()) != null)
{
Questions_Base oQuestions_Base = new Questions_Base(); // error here
oQuestions_Base.Import(B1String);
}
Please advice me.. thanks!
The purpose of an abstract class it to serve as part of a class hierarchy where more-derived classes share some common implementation.
If you have a flight simulator, you might define an abstract class ThingsThatFly that implements some properties (air speed, altitude, heading) and methods (TakeOff(), Land()) that all flying things have in common, but would be declared abstract because ThingsThatFly is an abstraction of all concrete things that fly. You could certainly have classes inbetween as well, for example Cessna172 could inherit from Airplane that inherits from ThingsThatFly. You would do that if all airplanes have some common implementation that e.g. birds don't have (for example, a Fuel Remaining property).
You would then have a number of concrete (= real life) things that fly like a Cessna 172, a Space Shuttle and a Duck. Each of those would be a concrete class that derives from ThingsThatFly
This is different than having the concrete classes implement an interface such as IThingsThatFly in that the abstract class provides not only a definition of the properties and methods that are expected, but also provides a (hopefully useful) implementation of those properties and methods.
An Abstract class can only be inherited.
public class CustomClass : Questions_Base {
}
Here's a link all about abstract classes and how to use them.
You cant create an instance of an abstract class.
You need to define a concrete class that inherits the abstract class, and create an instance of that.
Abstract class is made to be overriden by Derived class. If you have to have Abstract class, first create s Derived class from it and use Derived class contructor.
If it's not important, just remove abstract word from Questions_Base class declaration, so making that non abstract one. Also because in code provided I don't see any abstract member, so may this one is correct choice.
Regards.
An abstract class cannot be instantiated. You must provide an implementation for the class.
abstract class Animal
{
public abstract void Speak() { }
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Woof");
}
}
See MSDN on abstract for more information
From the documentation: "The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class."
The purpose of using abstract is exactly to prevent instantiation, because you only created the class to use as a base class and never want an instance created.
More here.
An abstract class is one which MUST be inherited.
It falls somewhere between an Interface, which defines only the interface that a class must implement and no implementation code and a class that you can create an instance of which defines both the interface and the implementation code. There are several abstract classes in the .NET framework such as CollectionBase. You cannot create an instance of CollectionBase, it is intended for you to create a class that inherits from it and extends it's capabilities.
You should simpley be able to remove the kwy work "abstract" from your class definition of Questions_Base or create a new class definition that inherits from it.
Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. What's special about them, is that you can't create an instance of them - if you try, you will get a compile error. Instead, you have to subclass them, as taught in the chapter on inheritance, and create an instance of your subclass. So when do you need an abstract class? It really depends on what you do. To be honest, you can go a long way without needing an abstract class, but they are great for specific things, like frameworks, which is why you will find quite a bit of abstract classes within the .NET framework it self. A good rule of thumb is that the name actually makes really good sense - abstract classes are very often, if not always, used to describe something abstract, something that is more of a concept than a real thing.
I am surprised to know that an abstract class in C# is possible with no abstract methods also.
abstract class AbstractDemo
{
public void show()
{
Console.WriteLine("In Show Method");
}
}
class MainDemo:AbstractDemo
{
public static void Main()
{
Console.WriteLine("In Main Method");
}
}
Any explaination ?
Sometimes you don't want to give the possibility to instantiate a class but you need this class as a base class for other classes.
The reason for choosing abstract classes over interfaces is that you can provide some basic implementation.
This is entirely valid, and occasionally useful if you want to provide event-like behaviour: provide an abstract class with all the "event handlers" implemented as virtual methods with a default behaviour of doing nothing.
I've also personally used this a lot for abstract remote API client classes where all methods throw exceptions: they're abstract for the purposes of test doubles, expecting our implementations to be the only production implementations, but allowing users to create their own test doubles either by hand or via mocking frameworks. Making the methods virtual instead of abstract means that new RPCs can be added without that being a breaking change.
A derived class can then override some of the methods, but doesn't have to override any specific one, because nothing's abstract. It still makes sense for the class to be abstract because an instance of the base class would be pointless (as everything would be a no-op).
This pattern is much more common in Java than C#, however - as in C# you'd normally just use "proper" events.
An abstract class is a class that must be extended before it can be used. This does not it any way mean that the function themselves must be abstract.
Take for example an Animal class
public abstract class Animal
{
void Move()
{
//whatever
}
}
public class Fish : Animal
{
void Swim()
{
}
}
public class Dog : Animal
{
void Bark()
{
}
}
All animals can move but only the fish can swim and the dog can bark.
Or for a real life example. I have an Asp.net MVC base controller I use in my application. It has some basic methods I need very often like GetCurrentUser() and a function I wrote to help with localization. It also takes care of tracking so I don't have to rewrite that code in all of my controllers. The class has about 200 lines of code but not a single abstract method.
I think you're confusing abstract classes with interfaces. Interfaces can't have methods with body, abstract classes can. There are times when you want to prevent user from instantiating an object of a specific class; but still provide some base functionality for the classes that derive from it; this is what an abstract class is useful for.
If your class is just a base for other classes and it does not have an full usablility - in other words as a base itselfe is not usable at all then you want to prevent from creating instances of it. In this case you can make abstract class without abstract members.
You could use abstract keyword on a class just to signal the compiler that it can only used inheriting from it, and not directly; In this case you are not oblied to put abstract member on the class.
This is equivalent to put in the class only one protected constructor, but using abstract is more clear and understandable.
No better explanation than MSDN it self
http://msdn.microsoft.com/en-us/library/aa645615(v=VS.71).aspx
An abstract class cannot be instantiated directly, and it is a
compile-time error to use the new
operator on an abstract class. While
it is possible to have variables and
values whose compile-time types are
abstract, such variables and values
will necessarily either be null or
contain references to instances of
non-abstract classes derived from the
abstract types.
An abstract class is permitted (but not required) to contain abstract
members.
An abstract class cannot be sealed.
We have heard that in abstract class, there must be an abstarct member. But when I compile the abstarct class without an abstract method, it compiles. It gives me surprise. Now I am unable to find the article which explain exact behavior of an abstarct class.