This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the difference between an abstract class and a static one?
Hello
I Would like to know what are all the differences between abstract classes and static classes in C#
When do I use what and why?
Is it true the abstract class is a class which we cannot create instances of it?
Thanks
I would like to know what are all the differences between abstract classes and static classes in C#.
Don't ask questions like that. I could spend hours listing hundreds of differences, none of which would be relevant to you.
What is the most important difference between abstract classes and static classes in C#?
That's more like it.
An abstract class is usually intended to model something in a type hierarchy. For example, a truck is a kind of vehicle, and an airplane is a kind of vehicle, so you might have a base class Vehicle and derived classes Truck and Airplane. But "Vehicle" is abstract; there are no vehicles which are just vehicles without being some more specific kind of thing. You represent that concept with an abstract class.
A static class by contrast is not intended to model anything at all. It's just a convenient way of storing a bunch of code. Really it shouldn't be a class at all; VB made a better choice by calling such things "modules" rather than "classes". Though technically they inherit from object, static classes are logically not really in a type hierarchy at all. They're just a bucket for holding static members.
Static classes are often used as containers of extension methods.
When do I use what and why?
Use an abstract class when you want to build a model of the form "an X is a kind of Y". Like "a Car is a kind of Vehicle" or "a Square is a kind of Shape" or "a Magazine is a kind of Publication", where the "Y" is an abstract concept. Don't use it for things like "an Employee is a kind of Person" -- Person should be concrete. Person is not an abstract concept; there are people who are just people, but there are no vehicles that are not something else.
Use a static class when you want to make extension methods, or when you have a bunch of code that fits logically together but does not associate with any object. For example, if you have a bunch of related math routines, that's a good candidate for a static class.
Is it true the abstract class is a class which we cannot create instances of it?
No. That is not true. You can create instances of an abstract class. You do so by creating an instance of a more derived class.
Vehicle v = new Car();
Clearly v refers to an instance of Vehicle, and therefore you can create an instance of an abstract class. What you cannot do is create an instance of an abstract class that is not also an instance of a more derived concrete class.
By contrast, you cannot create an instance of a static class at all.
Here's a question you didn't ask:
What is the implementation relationship between static classes and abstract classes?
Static classes actually do not really exist as a concept in the CLR. When you say "static" on a class, what we actually do is generate an abstract sealed class with no public constructors. Since it is abstract, you cannot create one directly. Since it is sealed, you cannot create a more derived class and instantiate that.
It's true that it's not possible to create an instance of an abstract or static class but that's about where the similarities end.
Can inherit from abstract cannot inherit from static
Can have instance methods on abstract cannot have instance on static
An abstract class can implement an interface a static class cannot
Fundamentally they are trying to serve two different purposes
An abstract class forms a blue print / pattern which is then implemented in derived classes in different and (hopefully) transparent ways
A static class is simply a container for a collection of possibly related static methods
An abstract class is a class that must be inherited to be used — it can only be inherited.
You can create instances of classes that inherit it.
A static class is a class that cannot have instances at all; such a class only has static members.
static classes cannot be inherited, nor can they inherit other classes.
True, an abstract class cannot be instantiated, but instead forms the base of other classes. The benefit is that you can put functionality into the abstract class to aid reuse.
A static class is one that is instantiated by the CLR when required. There can only be one instance of it any time. Using static classes is very useful, but care must be taken around threading and simultaneous access.
Related
Right now, I am learning OOP, mainly in c#. I am interested in what are the main reasons to make a class that can't be instantiated. What would be the correct example of when to make an abstract class?
I found myself using the abstract class in inheritance way too enthusiastically. Are there some rules when class is abstract in system and when class should not be abstract?
For instance, I made doctor and patient classes which are similar in some way so I derived them both from abstract class Person (since both have name and surname). Was that wrong?
Sorry if the question is stupid, I am very new at this.
There are a couple of things no one has pointed out so far, so I would just like to point them out.
You can only inherit from one base class (which could be abstract) but you can implement many interfaces. So in this sense inheriting an abstract class is a closer relationship than implementing an interface.
So if you later on realize that you have a need for a class which implements two different abstract classes you are in deep shit :)
To answer your question "when to make an abstract class" I'd say never, avoid it if possible, it will never pay off in the long run, if the main class is not suitable as a ordinary class, it probably isn't really needed as abstract either, use an interface. If you ever get in the situation where you are duplicating code it might be suitable with an abstract class, but always have a look at interfaces and behavioral patterns first (ex the strategy pattern solves a lot of issues people wrongly use inheritance to solve, always prefer composition over inheritance). Use abstract classes as a last hand solution, not as a design.
To get a better understanding of OOP in general, I'd recommend you to have a look at Design Patterns: Elements of Reusable Object-Oriented Software (a book) which gives a good overview of OO-design and reusability of OO-components. OO-design is about so much more than inheritance :)
For Example: you have a scenario where you need to pull data from different sources, like "Excel File,XML,any Database etc" and save in one common destination. It may be any database. So in this situation you can use abstract classes like this.
abstract class AbstractImporter
{
public abstract List<SoldProduct> FetchData();
public bool UploadData(List<SoldProduct> productsSold)
{
// here you can do code to save data in common destination
}
}
public class ExcelImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from excel
}
}
public class XMLImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from XML
}
}
public class AccessDataImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from Access database
}
}
and calling can be like this
static class Program
{
static void Main()
{
List<SoldProduct> lstProducts;
ExcelImporter excelImp = new ExcelImporter();
lstProducts = excelImp.FetchData();
excelImp.UploadData(lstProducts);
XMLImporter xmlImp = new XMLImporter ();
lstProducts = xmlImp.FetchData();
xmlImp.UploadData(lstProducts);
AccessDataImporterxmlImp accImp = new AccessDataImporter();
lstProducts = accImp .FetchData();
accImp.UploadData(lstProducts);
}
}
So, in Above example, implementation of data import functionality is separated in extended (derived) class but data upload functionality is common for all.
This is probably a non-academic definition, but an abstract class should represent an entity that is so "abstract" that make no sense to instantiate it.
It is often used to create "templates" that must be extended by concrete classes. So an abstract class can implement common features, for example implementing some methods of an interface, an delegate to concrete classes implementation of specific behaviors.
In essence what you have done is fine if you never want to instantiate a Person class, however as I'm guessing you may want to instantiate a Person class at some point in the future then it should not be abstract.
Although there is an argument that you code to fix current issues, not to cater for issues which may never arise, so if you need to instantiate Person class do not mark it as abstract.
Abstract classes are incomplete and must be implemented in a derived class... Generally speaking I tend to prefer abstract base classes over interfaces.
Look into the difference between abstract classes and interfaces...
"The difference between an abstract class and an interface is that an abstract class can have a default implementation of methods, so if you don't override them in a derived class, the abstract base class implementation is used. Interfaces cannot have any implementation." Taken from this SO post
As already stated, noone will force you to use abstract classes, it is just a methodology to abstract certain functionality which is common among a number of classes.
Your case is a good example where to use abstract classes, because you have common properties among two different types. But of cause it restricts you to use Person as a type by itself. If you want to have this restriction is basically up to you.
In general, I would not use abstract classes for Model like classes as you have unless you want to prevent Person from being instantiated.
Usually I use abstract classes if I also have defined an interface and I need to code different implementations for this interface but also want to have a BaseClass which already covers some common functionality for all implementations.
Deriving both 'Doctor' and 'Patient' from an abstract class 'Person' is fine, but you should probably make Person just a regular class. It depends on the context in which 'Person' is being used, though.
For example, you might have an abstract class named 'GameObject'. Every object in the game (e.g. Pistol, OneUp) extends 'GameObject'. But you can't have a 'GameObject' by itself, as 'GameObject' describes what a class should have, but doesn't go into detail as to what they are.
For example, GameObject might say something like: "All GameObjects must look like something'. A Pistol might extend on what GameObject said, and it says "All Pistols must look like a long barrel with a grip on one end and a trigger."
The key is whether instantiation of that class ever makes sense. If it will never be appropriate to instantiate that class, then it should be abstract.
A classic example is a Shape base class, with Square, Circle and Triangle child classes. A Shape should never be instantiated because by definition, you don't know what shape you want it to be. Therefore, it makes sense to make Shape an abstract class.
Incidentally, another issue which hasn't yet been mentioned is that it is possible to add members to an abstract class, have existing implementations automatically support them, and allow consumers to use implementations which know about the new members and implementations which don't, interchangeably. While there are some plausible mechanisms by which a future .NET runtime could allow interfaces to work that way as well, at present they do not.
For example, if IEnumerable had been an abstract class (there are of course good many reasons why it isn't), something like a Count method could have been added when its usefulness became apparent; its default implementation of Count could behave much like the IEnumerable<T>.Count extension method, but implementations which knew about the new method could implement it more efficiently (although IEnumerable<T>.Count will try to take advantage of implementations of ICollection<T>.Count or ICollection.Count, it first has to determine whether they exist; by contrast, any override would know that it has code to handle Count directly).
It would have been possible to add an ICountableEnumerable<T> interface which inherited from IEnumerable<T> but included Count, and existing code would continue to work just fine with IEnumerable<T> as it always had, but any time an ICountableEnumerable<T> was passed through existing code, the recipient would have to recast it to ICountableEnumerable<T> to use the Count method. Far less convenient than having a directly-dispatched Count method which could simply act directly on IEnumerable<T> [the Count extension method isn't horrible, but it's far less efficient than would be a directly-dispatched virtual method].
If there were a means by which an interface could include static methods, and if the class loader, upon finding that a class Boz which claimed to implement IFoo, was missing method string IFoo.Bar(int), would automatically add to that class:
stringIFoo.Bar(int p1) { return IFoo.classHelper_Bar(Boz this, int p1); }
[assuming the interface contains that static method], then it would be possible to have interfaces add members without breaking existing implementations, provided that they also included static methods that could be called by default implementations. Unfortunately, I know of no plans to add any such functionality.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to use an interface instead of an abstract class and vice versa?
Difference between Interface, abstract class, sealed class, static class and partial class in C#?
public class Guru{
public Enemy(int x, int y, int health, int attack, ...) {
...
}
...
}
public class UserDefinedClass extends Enemy {
...
}
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
An Interface cannot implement methods.
An abstract class can implement methods.
An Interface can only inherit from another Interface.
An abstract class can inherit from a class and one or more interfaces.
An Interface cannot contain fields.
An abstract class can contain fields.
An abstract class can not be instantiated but that can contain code whereas interface only contains method definitions but does not contain any code. you need to implement all the methods defined in the interface.
If your logic will be the same for all the derived classes, it is best to go for a abstract class in stead of an interface.
You can implement multiple interfaces but only inherit from one class.
oAn interface implies the minimal coupling possible between the object and the code that wants to consume it. An abstract class implies some stronger relationship between the classes, and probably some commonality of implementation.
An interface should be used when we want to separate concerns as much as possible (eg Dependency Injection)
An abstract class should be used to model a common family of objects where a strong relationship exists in the domain
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.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Difference between Interface, abstract class, sealed class, static class and partial class in c#? If all classes available in vb.net?
abstract class
Should be used when there is a IS-A relationship and no instances should be allowed to be created from that abstract class.
Example: An Animal is an abstract base class where specific animals can be derived from, i.e. Horse, Pig etc.
By making Animal abstract it is not allowed to create an Animal instance.
interface
An interface should be used to implement functionality in a class. Suppose we want a horse to be able to Jump, an interface IJumping can be created. By adding this interface to Horse, all methods in IJumping should be implemented. In IJumping itself only the declarations (e.g. StartJump and EndJump are defined), in Horse the implementations of these two methods should be added.
sealed class
By making Horse sealed, it is not possible to inherit from it, e.g. making classes like Pony or WorkHorse which you like to be inheriting from Horse.
static class
Mostly used for 'utility' functions. Suppose you need some method to calculate the average of some numbers to be used in the Horse class, but you don't want to put that in Horse since it is unrelated and it also is not related to animals, you can create a class to have this kind of methods. You don't need an instance of such a utility class.
partial class
A partial class is nothing more than splitting the file of a class into multiple smaller files. A reason to do this might be to share only part of the source code to others. If the reason is that the file gets too big, think about splitting the class in smaller classes first.
Interface: method definitions only
Abstract class: some method implementations, some methods abstract (method definition only)
Sealed class: A class from which you
may not inherit
Static class: a class with only
static methods (no instances
exist, all methods may be called
without an instance)
Partial class: A class that is
defined in 2 or more separate
class definitions in different
modules.
Yes, they are all available in both C# and VB, although VB uses different keywords in some cases.
I guess following link will be useful for you.
http://letschattechnology.com/interface-vs-abstract-classes/
the basic logical difference is you create abstract class when there is a relation between two classes that will inherit the abstract class and you create interface for the classes which are not related to each other but do have some common functionality.
A normal class can be instantiated at runtime to form an Object with fields (fields are properties, functions, events, etc). A normal class can also be inherited/sub-classed.
Adding one of the extra keywords change the way the class works.
Adding public, private, protected changes the way other code can see and use this class.
Adding static to a class means you can't create an instance with the new keyword but you can only access it through static function. Example: String.IsNullOrEmpty().
Adding sealed to a class means no other class can inherit the 'sealed' class.
Interfaces are contracts that say an implementing class will supply some functionality. The IDisposable interface says that all classes implementing it will have a Dispose function.
Following are the differences between abstract and interface:
Abstract classes have method declaration as well as method definition whereas interfaces have method declaration only.
Abstract classes are known as partial abstract classes whereas interfaces are known as fully abstract classes.
Abstract class features are inherited by child classes whereas interface features have to be implemented in implementing classes.
Abstract classes support access specifiers whereas interfaces don't support access specifiers.
Abstract classes have normal variables as well as constant variables whereas interfaces do not have variables.
We can write constructors in abstract classes whereas we can't write constructors in interfaces.
In abstract class can provide more functionality without affecting child class.
In interface,if we add any method to interface ,then it will affect all the child class.
Neither is instantiable. What are the differences, and in what situations might you use one or the other?
static indicates the class can only have static members and you cannot create an instance of it. This is used for stateless functionality (for example a type that just defines extension methods, or utility methods). You can also declare a member static on a non-static class. This allows you to attach functionality to a type without having to instantiate it.
Here's more detail on using static members and classes.
abstracts define the basic structure and functionality shared by all derivative types, but cannot be used by themselves. Think of them as, I suppose, a blue print and a contract. This is a core concept for OOP.
Here's more detail on using abstracts.
Here is a short summary:
A static class can only contain static members (it is just a container for methods that do not logically belong to an instance of any standard class)
An abstract class can contain all usual kinds of members (static, abstract and also instance)
The key difference is that you can inherit from an abstract class, but you cannot inherit from a static class. Technically speaking, the .NET runtime doesn't have any notion of static classes, so the C# compiler compiles them as classes that are both abstract and sealed (meaning that you cannot inherit from them).
So, static classes are abstract classes that are also sealed (although this is not the usual way to look at the problem if you are C# programmer) and contain only static members (which is enforced by the C# compiler).
An abstract class is intended to be used as a base of a class inheritance hierarchy. A static class cannot be the base of a class inheritance hierarchy.
A static class is intended for singleton state or stateless functionality. An abstract class is not suitable for singleton functionality, because, even though it may contain static methods and fields as a static class does, it cannot forbid inheritance, so the singleton use may be defeated by subclasses. Or, at the very least, it would be confusing to other programmers, because its definition would communicate an intent that is different from its actual intended use.
The superficial similarity between abstract and static classes is only in the fact that neither may be instantiated. Beyond that, they are completely different animals with completely different use cases.
The CLR has no notion of static classes, it is specific to C#. The compiler implements it by slick use of CLR attributes for a class: it declares it abstract and sealed. That prevents any language from instantiating such a class. This is what it looks like when you run Ildasm:
.class public abstract auto ansi sealed beforefieldinit ConsoleApplication1.Test
extends [mscorlib]System.Object
{
}
Making it sealed is very much the point of a static class, it is used as a container for static methods and fields. Which makes them act like global variables and functions like you have in languages like C or Pascal.
An abstract class is very much the opposite, it is designed to be derived from. A abstract class that has all of its member abstract acts like an interface. C# has a keyword for that, making static class and interface the exact opposites.
Abstract classes get instantiated indirectly via derived classes. They provide common behaviour and instance state, but signal that more is required and must be provided by derived concrete classes. For example, Transform might be an abstract class: it declares a common Apply(Shape) method, but no implementation of that method. Concrete derived classes like Rotation or Translation will implement that method, and those classes can be instantiated.
Static classes cannot be instantiated, and any state is at the class level rather than the instance level. They are typically used to define utility methods where there is no state associated with the methods. Transform couldn't be a static class, because the concrete derived classes need per-instance state (e.g. Rotation needs a per-instance Angle, because different Rotation transforms could be by different angles).
Abstract classes are intended to be used as base classes; they cannot have direct instances. Instead, you have to derive subclasses, which provide the what was (usually intentionally) left out in the abstract base class.
Example: consider you have a complex application, where users may log-in to. Various authentication mechanisms should be usable, say, LDAP, NTLM, you name it. One way to model a "user" or "principal" in such a context would be to collect, what is common across all those mechanisms, into an abstract base class, and leave "gaps" (abstract methods) where the actual implementations come into play:
abstract class Authenticator {
protected Dictionary<string,User> userCache;
...
public User LoadUser(string name) {
User user;
if( userCache.TryGet(name, out user) ) return user;
else {
user = LoadFromStore(name);
userCache.Add(name, user);
return user;
}
}
protected abstract User LoadFromStore(string name);
}
Here, caching of users is a common concern, modelled in the base case, whereas the actual retreival is left for a subclass to provide.
Static class are a different matter alltogether. They are essentially a place to keep your utility functions:
static class StrUtil {
public static string TrimWhitespace(string str) {
...
}
}
Think of them as some kind of special namespace, which can only contain static members. Basically, a place to put functions.
Abstract Class (Base class):
Enables other classes to inherit from this class (one class acquires the properties (methods and fields) of another) , but forbids to instantiate i.e we cannot have objects of this class.
http://csharp.net-tutorials.com/classes/abstract-classes
Static Class:
This class cannot be instantiated. Also this class cannot be inherited. To access methods of this class, you can directly use classname.method.
https://social.technet.microsoft.com/wiki/contents/articles/21028.difference-between-static-class-sealed-class-and-abstract-class-in-c.aspx
Abstract class main purpose is to define one or more abstract method(s).
Any class extending Abstract class will implement the abstract method or else its also need to be declared as "Abstract".
But, its also possible to declare a class as "Abstract" without implementing any abstract method(s) in it. See the sample below.
public abstract class AbstractTest {
public void abcd(){}
public static void main(String[] args) {
System.out.print("hi...");
}
}
Only inner class can be declared as "Static", see the code below.
Upper/encapsulating class can't be declared as "Static".
It can be accessed by using Upper/encapsulating class variable.Static-inner-classname i.e same as any static method invocation using class name.
public class StaticTest {
public static void main(String ag[]){
System.out.println("hello...1");
StaticTest.StaticTest2.meth2();
}
public static class StaticTest2 {
public static void meth2(){
System.out.print("hello...2");
}
}
}
Main difference between the two is extensibility.
CLR marks all 'static' classes as 'abstract & sealed' behind the scene (i.e., they cannot be inherited hence cannot be extended) and .NET Framework CLR loads them automatically when containing program or namespace is loaded. This gives performance gain on runtime.
Philosophy behind 'abstract' classes is capitalizing all common features of all extended classes in one place.
Hope it helps.